Compare commits

...

64 Commits

Author SHA1 Message Date
chengpeiquan
f065747b65
docs: add deprecation statement 2023-06-24 01:18:15 +08:00
chengpeiquan
74eee8344f
docs: add deprecation statement 2023-06-24 01:17:17 +08:00
chengpeiquan
7c2dc8487c
Merge pull request #20 from analyticsjs/dependabot/npm_and_yarn/ansi-regex-5.0.1
Bump ansi-regex from 5.0.0 to 5.0.1
2022-03-29 23:04:41 +08:00
dependabot[bot]
9599702cb6
Bump ansi-regex from 5.0.0 to 5.0.1
Bumps [ansi-regex](https://github.com/chalk/ansi-regex) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/chalk/ansi-regex/releases)
- [Commits](https://github.com/chalk/ansi-regex/compare/v5.0.0...v5.0.1)

---
updated-dependencies:
- dependency-name: ansi-regex
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-29 15:03:59 +00:00
chengpeiquan
33748b69e6
Merge pull request #19 from analyticsjs/dependabot/npm_and_yarn/minimist-1.2.6
Bump minimist from 1.2.5 to 1.2.6
2022-03-29 23:03:30 +08:00
dependabot[bot]
fa98889803
Bump minimist from 1.2.5 to 1.2.6
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-29 15:02:41 +00:00
chengpeiquan
a54ade27d1
Create codeql-analysis.yml 2021-08-31 19:59:26 +08:00
chengpeiquan
b2916bffed
Create SECURITY.md 2021-08-31 19:58:43 +08:00
chengpeiquan
93f8d306c4
Merge pull request #18 from analyticsjs/dependabot/npm_and_yarn/path-parse-1.0.7
Bump path-parse from 1.0.6 to 1.0.7
2021-08-31 19:58:17 +08:00
dependabot[bot]
22f0464913
Bump path-parse from 1.0.6 to 1.0.7
Bumps [path-parse](https://github.com/jbgutierrez/path-parse) from 1.0.6 to 1.0.7.
- [Release notes](https://github.com/jbgutierrez/path-parse/releases)
- [Commits](https://github.com/jbgutierrez/path-parse/commits/v1.0.7)

---
updated-dependencies:
- dependency-name: path-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-13 00:57:15 +00:00
chengpeiquan
67ad83991b
Merge pull request #17 from analyticsjs/develop
release: v2.2.0
2021-06-16 11:42:40 +08:00
chengpeiquan
9158f04e4d
Merge branch 'master' into develop 2021-06-16 11:42:31 +08:00
程沛权
00336ceb4d chore: update README 2021-06-16 11:38:19 +08:00
程沛权
6d71e9dba3 chore: update README 2021-06-16 11:34:12 +08:00
程沛权
80ee80cc33 chore: update README 2021-06-16 11:30:05 +08:00
程沛权
6e29068e95 chore: add verify commit script 2021-06-16 11:28:37 +08:00
程沛权
708a418598 test commit lint 2021-06-16 11:21:21 +08:00
程沛权
b4457614a9 chore: update README 2021-06-16 11:16:30 +08:00
程沛权
3d37199fdc chore: update README 2021-06-15 18:32:49 +08:00
程沛权
3aad6404e1 chore: update eslint ignore 2021-06-15 18:16:27 +08:00
程沛权
69ecd02121 feat: now, the vue router is optional 2021-06-15 18:15:02 +08:00
程沛权
cb18c6892e chore: rename some files 2021-06-15 17:50:13 +08:00
程沛权
ed3e666286 chore: update eslint rule 2021-06-15 17:27:17 +08:00
程沛权
900b744a5b chore: update eslint rule 2021-06-15 17:17:20 +08:00
程沛权
3ad117891b chore: test git hooks 2021-06-15 15:33:57 +08:00
程沛权
fc0b4a7590 chore: test git hooks 2021-06-15 15:29:06 +08:00
程沛权
03077c8e3e chore: test git hooks 2021-06-15 15:27:47 +08:00
程沛权
e718db556d chore: test git hooks 2021-06-15 15:23:21 +08:00
程沛权
87d46b37cd chore: test git hooks 2021-06-15 15:22:46 +08:00
chengpeiquan
2071c89e40
Merge pull request #16 from analyticsjs/dependabot/npm_and_yarn/browserslist-4.16.6
Bump browserslist from 4.16.3 to 4.16.6
2021-05-28 01:24:49 +08:00
dependabot[bot]
5146e16c44
Bump browserslist from 4.16.3 to 4.16.6
Bumps [browserslist](https://github.com/browserslist/browserslist) from 4.16.3 to 4.16.6.
- [Release notes](https://github.com/browserslist/browserslist/releases)
- [Changelog](https://github.com/browserslist/browserslist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/browserslist/browserslist/compare/4.16.3...4.16.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-27 02:09:59 +00:00
chengpeiquan
8f3a4c8aa2
Merge pull request #15 from analyticsjs/develop
Update README.
2021-04-05 02:04:27 +08:00
chengpeiquan
326b1833cf Update README. 2021-04-05 02:03:35 +08:00
chengpeiquan
02fa4512d8 Update README. 2021-04-05 02:03:01 +08:00
chengpeiquan
7b3e12053f
Merge pull request #14 from analyticsjs/develop
Update suffix.
2021-04-05 01:54:03 +08:00
chengpeiquan
a9678c8fec Update suffix. 2021-04-05 01:53:31 +08:00
chengpeiquan
6401dbd6d7
Merge pull request #13 from analyticsjs/develop
Update README.
2021-04-05 01:49:11 +08:00
chengpeiquan
cb1158e4c4 Update README. 2021-04-05 01:48:46 +08:00
chengpeiquan
e3251ace0a
Merge pull request #12 from analyticsjs/develop
Update Links in README.
2021-04-04 23:58:02 +08:00
chengpeiquan
501d647086 Update Links in README. 2021-04-04 23:57:43 +08:00
chengpeiquan
daba71481c Update Links in README. 2021-04-04 23:56:18 +08:00
chengpeiquan
66da1627f6
Merge pull request #11 from analyticsjs/develop
Release v2.1.0
2021-04-04 23:54:36 +08:00
chengpeiquan
f9ca4e0f3b Release v2.1.0 2021-04-04 23:53:57 +08:00
chengpeiquan
173917b754
Merge pull request #10 from analyticsjs/develop
Release v2.1.0
2021-04-04 23:51:52 +08:00
chengpeiquan
e97f961068 Release v2.1.0 2021-04-04 23:51:10 +08:00
chengpeiquan
fa9a822442 Update FUNDING. 2021-04-04 17:59:45 +08:00
chengpeiquan
d7bfd85c6b
Merge pull request #9 from analyticsjs/develop
Release v2.1.0
2021-04-04 17:58:42 +08:00
chengpeiquan
c4351c2e3c Update FUNDING. 2021-04-04 17:57:40 +08:00
chengpeiquan
60fe21cfd9 Update FUNDING. 2021-04-04 17:55:49 +08:00
chengpeiquan
3ad286ffeb Release v2.1.0 2021-04-04 17:53:36 +08:00
chengpeiquan
047a6f16ce
Merge pull request #8 from chengpeiquan/develop
update FUNDING
2021-01-11 15:12:01 +08:00
chengpeiquan
802231dc90 update FUNDING 2021-01-11 15:10:28 +08:00
chengpeiquan
1299528637
Merge pull request #7 from chengpeiquan/develop
Release v2.0.3
2021-01-11 14:31:08 +08:00
chengpeiquan
217bb57750 Release v2.0.3 2021-01-11 14:29:47 +08:00
chengpeiquan
d3150001ce
Merge pull request #6 from chengpeiquan/develop
Develop
2021-01-11 11:44:19 +08:00
chengpeiquan
4aff1f5eac Release v2.0.2 2021-01-11 11:43:23 +08:00
chengpeiquan
fedfa49e5e Update README 2021-01-11 11:42:43 +08:00
chengpeiquan
cb63eaa601 Update package.json 2021-01-11 11:42:05 +08:00
chengpeiquan
263757f20e Update README 2021-01-11 11:41:36 +08:00
chengpeiquan
a1da25c8e4 Update variable type. 2021-01-11 11:40:13 +08:00
chengpeiquan
2bbebe8b14 fix: Vue 3.0 路由mode判断错误的问题 2021-01-11 11:36:52 +08:00
chengpeiquan
377337d53b
Merge pull request #5 from chengpeiquan/develop
Develop
2021-01-08 23:45:48 +08:00
chengpeiquan
f96c833ca0 Release v2.0.1 2021-01-08 23:43:22 +08:00
chengpeiquan
351af146c0 Release v2.0.1 2021-01-08 23:42:51 +08:00
34 changed files with 4583 additions and 2492 deletions

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
dist/*
demo/*

18
.eslintrc.js Normal file
View File

@ -0,0 +1,18 @@
module.exports = {
root: true,
env: {
node: true,
browser: true,
},
extends: ['eslint:recommended', 'prettier'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2020,
},
plugins: ['@typescript-eslint', 'prettier'],
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'prettier/prettier': 'warn',
},
}

12
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1,12 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: https://github.com/chengpeiquan/sponsor

71
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,71 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '30 16 * * 2'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"semi": false,
"singleQuote": true
}

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 chengpeiquan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

319
README.en.md Normal file
View File

@ -0,0 +1,319 @@
This package is no longer maintained, please use [@web-analytics/vue](https://analytics.js.org/vue/) , which has an easier method of use while maintaining the original functions.
---
<p align='center'>
<img src="https://cdn.jsdelivr.net/gh/chengpeiquan/assets-storage/img/2021/04/20210404235335.png" alt="vue-baidu-analytics" />
</p>
<p align='center'>
<a href='https://www.npmjs.com/package/vue-baidu-analytics'>
<img src="https://img.shields.io/npm/v/vue-baidu-analytics?color=41b883&label=npm" />
</a>
</p>
<br>
<br>
[简体中文](https://github.com/analyticsjs/vue-baidu-analytics/blob/master/README.md) | English
Only 3 kB, this plugin base on the Baidu analytics, it can help you quickly to collect the page views on your website, including single page web application.
>Since the version v2.0.0, it supports the Vue 3.0, and is compatible with the Vue 2.0, you can see the live demo to learn more.<br>If you havent started using Vue 3.0, welcome to read the tutorial [learning Vue3](https://vue3.chengpeiquan.com/) .
## Features
* Asynchronously load the Baidu analytics scripts, no need to modify the entry HTML.
* Support the deployment of multiple site IDs and corresponding data reporting.
* Supports automatic reporting of PV data generated by route switching (This feature need [Vue Router](https://router.vuejs.org/), It can support hash mode and history mode).
* Support manual submission of page views reports.
* Support manual submission of event reports.
* Since the version v2.0.0, the plugin can automatically recognize the Vue version at Vue 2.0 or Vue 3.0 .
* Since the version v2.1.0, Hooks API is provided (So the usage of CDN installation is slightly adjusted)
## Project
As long as Vue and Vue Router are introduced, the projects can be used normally, no matter what method is used to develop your project, e.g. :
* Vue-CLI scaffolding project
* Vite project
* Introduce the HTML page of Vue related CDN
* VuePress project
It is not limited to SPA single page projects, it can also be used in SSG / SSR projects.
## Preview
Both live demos have enabled debug mode, and you can open the console to view the report.
Vue 2.0 [vue-baidu-analytics demo for Vue 2.x](https://analyticsjs.github.io/vue-baidu-analytics/demo/vue2.html "vue-baidu-analytics demo for Vue 2.x")
Vue 3.0 [vue-baidu-analytics demo for Vue 3.x](https://analyticsjs.github.io/vue-baidu-analytics/demo/vue3.html "vue-baidu-analytics demo for Vue 3.x")
## Options
Option|Required|Type|Description
:-:|:-:|:-:|-
router|false|object|Vue Router(It is optional since v2.2.0.)
siteIdList|true|string[]|The site ids for Baidu analytics, if only one site needs to be reported, just keep one item in the array.
isDebug|false|boolean|if `true`, it will open the debug modeyou can see the log in the console.
Tips: Please remember to turn off the debug mode before publish.
## Install
You can install the plugin from NPM.
```bash
npm install vue-baidu-analytics --save-dev
```
Can also use the CDN URL in your HTML.
```html
<script src="https://cdn.jsdelivr.net/npm/vue-baidu-analytics/dist/vue-baidu-analytics.min.js"></script>
```
## Usage
If use NPM, you must import the plugin in `main.js` .
```js
import baiduAnalytics from 'vue-baidu-analytics'
```
Then, refer to the sample code in Vue 2.0 and Vue 3.0 below to use it.
When the route is switched, the new URL address will be reported to Baidu analytics after the visit.
### Use in the Vue 2.0
See[main.js - Vue 2.0 demo](https://analyticsjs.github.io/vue-baidu-analytics/demo/js/main-for-vue2.js)
>Since the version v2.1.0, if you use CDN in your HTML, must be use `baiduAnalytics.default` to use the plugin.
```js
Vue.use(baiduAnalytics, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb'
],
isDebug: false
});
```
### Use in the Vue 3.0
See[main.js - Vue 3.0 demo](https://analyticsjs.github.io/vue-baidu-analytics/demo/js/main-for-vue3.js)
>Since the version v2.1.0, if you use CDN in your HTML, must be use `baiduAnalytics.default` to use the plugin.
```js
createApp(app)
.use(router)
.use(baiduAnalytics, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb'
],
isDebug: false
})
.mount('#app');
```
### Use in the VuePress
The plugin can also be used in [VuePress](https://vuepress.vuejs.org/zh/) project.
In the `/docs/.vuepress` folder under the project, create a file named `enhanceApp.js`, and write the following code in this file.
You can see [App Level Enhancements - VuePress](https://vuepress.vuejs.org/guide/basic-config.html#app-level-enhancements) to learn more.
```js
import baiduAnalytics from 'vue-baidu-analytics'
export default ({ Vue, router }) => {
Vue.use(baiduAnalytics, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc'
],
isDebug: false
});
};
```
You can turn on the debug mode in the development environment to learn about related reports (remember to turn off debug before going online).
## API
Since the version v2.1.0, you can use the Global API `$pushBAIDU` and the Hooks API `usePush` in your project, they both support the Vue 2.0 and 3.0.
>The APIs can't be used directly, it needs to cooperate with the [Methods](#Methods) to operate the specific functions.
### The Global API
In the Vue 2.0:
```js
// xxx.vue in Vue 2.0
export default {
// ...
mounted () {
this.$pushBAIDU.pv('/example-url/');
},
// ...
}
```
In the Vue 3.0, you can use the Global Properties:
```js
// xxx.vue in Vue 3.0
import { getCurrentInstance } from 'vue'
export default {
setup () {
const app = getCurrentInstance();
app.appContext.config.globalProperties.$pushBAIDU.pv('/example-url/');
}
}
```
You can also import the proxy component in the current instance to operate:
```js
// xxx.vue in Vue 3.0
import { getCurrentInstance } from 'vue'
export default {
setup () {
const { proxy } = getCurrentInstance();
proxy.$pushBAIDU.pv('/example-url/');
}
}
```
### The Hooks API
In the Vue 2.0:
```js
// xxx.vue in Vue 2.0
import { usePush } from 'vue-baidu-analytics'
export default {
// ...
data () {
return {
baidu: usePush()
}
},
mounted () {
this.baidu.pv('/example-url/');
},
// ...
}
```
In the Vue 3.0, just use it as if you were using the route `const router = useRouter();`.
```js
// xxx.vue in Vue 3.0
import { usePush } from 'vue-baidu-analytics'
export default {
setup () {
const baidu = usePush();
baidu.pv('/example-url/');
}
}
```
If the name of the hook API has already been declared, you can rename it when import.
```js
import { usePush as useBaidu } from 'vue-baidu-analytics'
const baidu = useBaidu();
```
## Methods
All methods are needs to be triggered through the API, and the methods supported by the Global API and the Hooks API are exactly the same.
Method|Description
:--|:--
Manually report the page views|[Click here to see.](#manually-report-the-page-views)
Manually report the event analysis|[Click here to see.](#manually-report-the-event-analysis)
>Since there are still many users of Vue 2.0, the following examples only use the operation method of Vue 2.0 to demonstrate. Vue 3.0 can call specific methods according to the description of the Hooks API.
Tips: If multiple site IDs are configured, the data will be reported to all sites at the same time.
### Manually report the page views
If you switch content rendering on some pages through Tab, but you need to report access data, you can use this method to manually report.
Method|Description
:-:|-
pv|Manually perform PV data reporting.
**Params**
Param|Required|Type|Description
:-:|:-:|:-:|-
pageUrl|false|string|The URL submitted for the report must be a relative path starting with `/`, if not filled, it will be submitted as the domain name root directory by default.
**Example**
```js
this.$pushBAIDU.pv('/example-url/');
```
### Manually report the event analysis
For example, there is a "exchange" function button on your page. If you want to count the clicks of this button, you can perform click analysis by binding the button to report events.
Method|Description
:-:|-
event|Manually perform event analysis data reporting.
**Params**
Param|Required|Type|Description
:-:|:-:|:-:|-
category|true|string|The name of the location where the event occurred, e.g. `banner`
action|true|string|The description of the behavior that generated the event, e.g. `click`
label|false|string|The name of the label that generated the event can be used to record the event sub-id, e.g. `bannerId_123`. (@default: '')
value|false|number|The score of the event. (@default: 0)
**Example**
```js
this.$pushBAIDU.event(
this.category,
this.action,
this.label,
this.value
);
```
## CHANGELOG
See[releases](https://github.com/analyticsjs/vue-baidu-analytics/releases)
## License
[MIT License](https://github.com/analyticsjs/vue-baidu-analytics/blob/master/LICENSE) © 2019 [chengpeiquan](https://github.com/chengpeiquan)

295
README.md
View File

@ -1,77 +1,112 @@
vue-baidu-analytics 使用说明
===
本包不再维护,请使用 [@web-analytics/vue](https://analytics.js.org/vue/) ,在保持原有功能的基础上,具有更简单的使用方法。
基于Vue开发的百度统计插件可以在 `Vue-CLI脚手架项目` 或者 `引入了Vue相关CDN的普通页面` 上使用,使用本插件的项目需要引入 `Vue Router`
---
> @v2.0版本更新:<br>最新版支持 Vue 3.x同时兼容 Vue 2.x 使用具体使用方法请看下方说明及demo。<br>对Vue 3.0感兴趣,但还在观望的同学,欢迎阅读我踩坑总结的:[Vue 3.0 学习教程](https://vue3.chengpeiquan.com/) 持续更新ing
<p align='center'>
<img src="https://cdn.jsdelivr.net/gh/chengpeiquan/assets-storage/img/2021/04/20210404235335.png" alt="vue-baidu-analytics" />
</p>
<p align='center'>
<a href='https://www.npmjs.com/package/vue-baidu-analytics'>
<img src="https://img.shields.io/npm/v/vue-baidu-analytics?color=41b883&label=npm" />
</a>
</p>
<br>
<br>
简体中文 | [English](https://github.com/analyticsjs/vue-baidu-analytics/blob/master/README.en.md)
一个只有 3 kB 大小的插件,可以帮你轻松解决 SPA 单页面项目浏览数据不准确的问题,可基于 Vue 路由访问轨迹自动向百度统计平台上报 PV / 事件数据。
>本插件自 v2.0.0 开始,最新版插件支持在 Vue 3.0 项目下使用,同时兼容 Vue 2.0 项目的使用,具体使用方法请看下方说明以及在线 demo 。<br>对 Vue 3.0 感兴趣,但还在观望的同学,欢迎阅读我踩坑总结的:[Vue3.0学习教程与实战案例](https://vue3.chengpeiquan.com/) 持续更新ing
## 功能
* 异步载入百度统计脚本无需修改入口html
* 异步载入百度统计脚本,无需修改入口 HTML
* 支持部署多个站点id并对应进行数据上报
* 支持部署多个站点 ID ,并对应进行数据上报(跨部门合作项目,双方均要收集数据时非常有用)
* 支持自动上报路由切换产生的pv数据支持 `hash模式``history模式` 的地址)
* 支持自动上报路由切换产生的 PV 数据(需引入 [Vue Router](https://router.vuejs.org/),支持 hash 模式和 history 模式的地址)
* 支持手动提交pv上报
* 支持手动提交 PV 上报
* 支持手动提交事件分析上报
* 自动识别Vue版本自动适配Vue 2.0/3.0使用插件2.0版本新增)
* 自动识别 Vue 版本,自动适配 Vue 2.0 / Vue 3.0 使用(本插件 v2.0.0 版本新增)
* 提供了 Hooks API本插件 v2.1.0 版本新增,因此 CDN 安装的用法略有调整,请留意使用说明)
## 项目
理论上只要引入了 Vue (必须) 和 Vue Router (自 v2.2.0 起是可选) 的项目均可以正常使用,包括但不限于以下类型:
* Vue-CLI 脚手架项目
* Vite 项目
* 引入 Vue 相关 CDN 的 HTML 页面
* VuePress 项目
也不仅限于 SPA 单页面项目,在 SSG / SSR 项目里也可以使用。
## 预览
demo已开启debug模式可开启控制台查看上报情况。
两个在线 demo已开启 debug 模式,可开启控制台查看上报情况。
Vue 2.0 版本:[vue-baidu-analytics demo for Vue 2.x](https://chengpeiquan.github.io/vue-baidu-analytics/demo/vue2.html "vue-baidu-analytics demo for Vue 2.x")
Vue 2.0 版本:[vue-baidu-analytics demo for Vue 2.x](https://analyticsjs.github.io/vue-baidu-analytics/demo/vue2.html "vue-baidu-analytics demo for Vue 2.x")
Vue 3.0 版本:[vue-baidu-analytics demo for Vue 3.x](https://chengpeiquan.github.io/vue-baidu-analytics/demo/vue3.html "vue-baidu-analytics demo for Vue 3.x")
Vue 3.0 版本:[vue-baidu-analytics demo for Vue 3.x](https://analyticsjs.github.io/vue-baidu-analytics/demo/vue3.html "vue-baidu-analytics demo for Vue 3.x")
## 选项
选项|是否必填|选项类型|选项说明
:-:|:-:|:-:|-
router|否|object|Vue Router自 v2.2.0 版本开始为可选,无路由的单页则不必传该选项)
siteIdList|是|string[]|百度统计的站点 id 列表,只有一个站点需要上报就保留一个 id 即可
isDebug|否|boolean|是否开启 debug 模式,默认 `false`,开启后会在 F12 控制台打印上报信息
友情提示:上线前记得关闭 debug 模式。
## 安装
方式一通过npm安装
方式一:通过 NPM 安装
```
```bash
npm install vue-baidu-analytics --save-dev
```
方式二通过cdn安装
方式二:通过 CDN 安装
```html
<script src="https://cdn.jsdelivr.net/npm/vue-baidu-analytics/dist/vue-baidu-analytics.min.js"></script>
```
## 参数
## 启用
参数|是否必填|参数类型|参数说明
:-:|:-:|:-:|-
router|是|object|Vue Router本插件基于路由使用
siteIdList|是|object Array|百度统计的站点id列表item为站点id<br>只有一个站点需要上报就保留一个item即可
isDebug|否|boolean|是否开启debug模式默认 `false`<br>开启后会在控制台打印上报信息,**上线前记得关闭**
## 使用
通过npm安装的项目需要先在 `main.js` 里引入插件通过cdn则无需该步骤
通过 NPM 安装的项目,需要先在 main.js 里引入插件(通过 CDN 则无需该步骤)。
```js
import baiduAnalytics from 'vue-baidu-analytics'
```
安装插件后,在 `main.js` 引入以下代码注意区分Vue2.0和Vue3.0的用法区别),即可开启自动上报功能,首次访问页面会部署统计代码并提交第一次访问数据上报。
安装插件后,在 main.js 引入以下代码(注意 Vue 2.0 和 Vue 3.0 的用法区别),即可开启自动上报功能,首次访问页面会部署统计代码并提交第一次访问数据上报。
后续在路由切换过程中,也会根据路由的切换提交相应的url信息到友盟统计。
后续在路由切换过程中,也会根据路由的切换提交相应的 URL 信息到百度统计。
### 在 Vue 2.0 里使用
可参考demo[main.js - Vue 2.0 demo](https://chengpeiquan.github.io/vue-baidu-analytics/demo/js/main-for-vue2.js)
可参考demo[main.js - Vue 2.0 demo](https://analyticsjs.github.io/vue-baidu-analytics/demo/js/main-for-vue2.js)
>自 v2.1.0 版本开始,如果是通过 CDN 安装,需要使用 `baiduAnalytics.default` 去激活插件,通过 NPM 安装的脚手架项目则使用 `baiduAnalytics` 就可以
```js
// 启动插件
Vue.use(baiduAnalytics, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc'
'bbbbbbbbbbbbbbbbbbb'
],
isDebug: false
});
@ -79,7 +114,9 @@ Vue.use(baiduAnalytics, {
### 在 Vue 3.0 里使用
可参考demo[main.js - Vue 3.0 demo](https://chengpeiquan.github.io/vue-baidu-analytics/demo/js/main-for-vue3.js)
可参考demo[main.js - Vue 3.0 demo](https://analyticsjs.github.io/vue-baidu-analytics/demo/js/main-for-vue3.js)
>自 v2.1.0 版本开始,如果是通过 CDN 安装,需要使用 `baiduAnalytics.default` 去激活插件,通过 NPM 安装的脚手架项目则使用 `baiduAnalytics` 就可以
```js
/**
@ -94,73 +131,194 @@ createApp(app)
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc'
'bbbbbbbbbbbbbbbbbbb'
],
isDebug: true
isDebug: false
})
// 挂载到节点上
.mount('#app');
```
可在开发环境打开debug模式了解相关的上报情况上线前记得关闭debug
### 在 VuePress 里使用
插件也支持在Vue的静态文档 [VuePress](https://vuepress.vuejs.org/zh/) 项目里使用。
在项目下的 `/docs/.vuepress` 文件夹下,创建一个 `enhanceApp.js`,按照下面的方式引入即可启动数据上报功能。
官方文档传送门:[应用级别的配置 - VuePress](https://vuepress.vuejs.org/zh/guide/basic-config.html#%E5%BA%94%E7%94%A8%E7%BA%A7%E5%88%AB%E7%9A%84%E9%85%8D%E7%BD%AE)
```js
import baiduAnalytics from 'vue-baidu-analytics'
export default ({ Vue, router }) => {
Vue.use(baiduAnalytics, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc'
],
isDebug: false
});
};
```
可在开发环境打开 debug 模式了解相关的上报情况(上线前记得关闭 debug )。
## API
自 v2.1.0 版本开始,插件支持直接调用的全局 API `$pushBAIDU` 和按需导入的钩子 API `usePush` 两种方式。
这两种方式在 Vue 2.0 和 3.0 里均可以使用,只不过按照使用习惯和从 Vue 官方推荐的角度来说,全局 API 更适合 Vue 2.0 项目,钩子 API 更适合 Vue 3.0 项目。
> 插件的 API 不可以直接使用,需要配合 API 里面的 [方法](#方法) 才可以操作到具体功能。
### 全局 API
在 Vue 2.0 里,只需要通过我们熟悉的 `this` 去操作即可:
```js
// xxx.vue in Vue 2.0
export default {
// ...
mounted () {
this.$pushBAIDU.pv('/example-url/');
},
// ...
}
```
在 Vue 3.0 里,可以按照官方文档的推荐,导入当前实例变量,通过当前实例变量去操作全局方法:
```js
// xxx.vue in Vue 3.0
import { getCurrentInstance } from 'vue'
export default {
setup () {
const app = getCurrentInstance();
app.appContext.config.globalProperties.$pushBAIDU.pv('/example-url/');
}
}
```
也可以导入当前实例里的代理组件去操作:
```js
// xxx.vue in Vue 3.0
import { getCurrentInstance } from 'vue'
export default {
setup () {
const { proxy } = getCurrentInstance();
proxy.$pushBAIDU.pv('/example-url/');
}
}
```
### 钩子 API
>钩子 API 需要在用到的组件里 import 导入才可以使用。
在 Vue 2.0 里,你可以绑定一个钩子变量去使用:
```js
// xxx.vue in Vue 2.0
import { usePush } from 'vue-baidu-analytics'
export default {
// ...
data () {
return {
// 创建钩子变量
baidu: usePush()
}
},
mounted () {
// 通过钩子变量去触发方法
this.baidu.pv('/example-url/');
},
// ...
}
```
在 Vue 3.0 里,就像在使用路由 `const router = useRouter();` 一样去使用就可以。
```js
// xxx.vue in Vue 3.0
import { usePush } from 'vue-baidu-analytics'
export default {
setup () {
// 创建钩子变量
const baidu = usePush();
// 通过钩子变量去触发方法
baidu.pv('/example-url/');
}
}
```
另外,如果 API 与其他插件冲突的话(比如你同时使用了 [vue-cnzz-analytics](https://github.com/analyticsjs/vue-cnzz-analytics)),你可以在导入的时候重命名:
```js
import { usePush as useBaidu } from 'vue-baidu-analytics'
const baidu = useBaidu();
```
## 方法
插件目前封装了两个常用的api统一挂载到Vue实例上的 `$pushBAIDU` 去调用。
方法需要通过 API 去触发,全局 API 和 钩子 API 支持的方法都是完全一样的
如果配置了多个站点id会同时上报给所有站点。
方法功能|使用说明
:--|:--
手动上报页面 PV|[点击查看](#手动上报页面PV)
手动上报事件分析|[点击查看](#手动上报事件分析)
### 手动上报页面PV
> 由于目前 Vue 2.0 的使用者还比较多,下面的举例均只用 Vue 2.0 的操作方法进行演示Vue 3.0 可根据钩子 API 的说明去调用具体的方法。
api名称|功能说明
注:如果配置了多个站点 ID ,数据都会同时上报给所有站点。
### 手动上报页面 PV
如果你有些页面是通过 Tab 切页进行内容渲染切换,但又需要上报访问数据的话,就可以使用这个方法来进行手动上报。
方法名称|功能说明
:-:|-
pv|手动执行PV数据上报
pv|手动执行 PV 数据上报
**api参数**
**参数**
参数|是否必填|参数类型|参数说明
:-:|:-:|:-:|-
pageUrl|否|String|提交上报的url必须是以 `/` 开头的相对路径<br>如果不填,则会默认提交为域名根目录
pageUrl|否|string|提交上报的 URL ,必须是以 `/` 开头的相对路径,如果不填,则会默认提交为域名根目录
**使用示范**
在 Vue 2.0 里使用
```js
this.$pushBAIDU.pv(this.pageUrl);
```
在 Vue 3.0 里使用
使用3.0的生命周期需要遵循Vue3的规范引入一个Vue自带的代理组件并写在 `setup` 里执行)
```js
const { proxy } = getCurrentInstance();
proxy.$pushBAIDU.pv(pageUrl.value);
this.$pushBAIDU.pv('/example-url/');
```
### 手动上报事件分析
api名称|功能说明
比如你的页面上有个 “换一换” 的功能按钮,想要统计这个按钮的点击情况,就可以通过给按钮绑定上报事件来进行点击情况分析。
方法名称|功能说明
:-:|-
event|手动执行事件分析数据上报
**api参数**
**参数**
参数|是否必填|参数类型|参数说明
:-:|:-:|:-:|-
category|是|string|产生该事件的位置名称,比如 `首页banner`
action|是|string|产生该事件的行为描述,比如 `点击`
label|否|string|产生该事件的标签名称可以用来记录事件子id比如 `bannerId_123`,默认为空
value|否|number|该事件的分值默认0
label|否|string|产生该事件的标签名称,可以用来记录事件子 id比如 `bannerId_123`,默认为空
value|否|number|该事件的分值,默认 0
**使用示范**
在 Vue 2.0 里使用
```js
this.$pushBAIDU.event(
this.category,
@ -170,17 +328,10 @@ this.$pushBAIDU.event(
);
```
在 Vue 3.0 里使用
## 更新记录
使用3.0的生命周期需要遵循Vue3的规范引入一个Vue自带的代理组件并写在 `setup` 里执行)
点击查看:[releases](https://github.com/analyticsjs/vue-baidu-analytics/releases)
```js
const { proxy } = getCurrentInstance();
## License
proxy.$pushBAIDU.event(
category.value,
action.value,
label.value,
value.value
);
```
[MIT License](https://github.com/analyticsjs/vue-baidu-analytics/blob/master/LICENSE) © 2019 [chengpeiquan](https://github.com/chengpeiquan)

21
SECURITY.md Normal file
View File

@ -0,0 +1,21 @@
# Security Policy
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| 5.1.x | :white_check_mark: |
| 5.0.x | :x: |
| 4.0.x | :white_check_mark: |
| < 4.0 | :x: |
## Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.

View File

@ -1,4 +1,4 @@
/**
/**
* 初始化路由
* routes是来自 js/routes.js 里面的配置
*/
@ -9,21 +9,21 @@ const router = new VueRouter({
});
/**
/**
* 引入统计插件
* @description v2.1.0 版本开始需要使用 .default 去激活插件
*/
Vue.use(baiduAnalytics, {
Vue.use(baiduAnalytics.default, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc'
'bbbbbbbbbbbbbbbbbbb'
],
isDebug: true
});
/**
/**
* 初始化Vue
*/
const app = new Vue({
@ -35,17 +35,43 @@ const app = new Vue({
category: '',
action: '',
label: '',
value: ''
value: '',
// 也可以绑定一个钩子变量去使用
baidu: baiduAnalytics.usePush()
}
},
mounted () {
this.baidu.pv('/use-push-api/?from=mounted');
},
methods: {
/**
* 提交 pv
* @description 支持两种推送方式
*/
pv () {
// 使用默认全局 API
this.$pushBAIDU.pv(this.pageUrl);
// 使用钩子 API
// this.baidu.pv(this.pageUrl);
},
/**
* 提交事件
* @description 支持两种推送方式
*/
event () {
this.$pushBAIDU.event(
// 使用默认全局 API
// this.$pushBAIDU.event(
// this.category,
// this.action,
// this.label,
// this.value
// );
// 使用钩子 API
this.baidu.event(
this.category,
this.action,
this.label,
@ -53,4 +79,4 @@ const app = new Vue({
);
}
}
});
});

View File

@ -1,11 +1,12 @@
/**
/**
* 导入需要用到的组件
*/
const { createRouter, createWebHashHistory } = VueRouter;
const { createApp, getCurrentInstance, ref } = Vue;
const { usePush } = baiduAnalytics;
/**
/**
* 初始化路由
* routes是来自 js/routes.js 里面的配置
*/
@ -17,13 +18,24 @@ const router = createRouter({
});
/**
/**
* 创建实例
*/
const app = {
setup () {
// 插件要用到的一个代理组件
const { proxy } = getCurrentInstance();
/**
* 新的推荐方式
* @description 创建一个钩子变量去使用更适合于 TypeScript 项目
*/
const baidu = usePush();
/**
* 原来的方式
* @description 从当前实例里导入代理组件去操作 TS 项目不够友好
*/
// const instance = getCurrentInstance();
// const { proxy } = instance;
// 初始化要用到的数据
const pageUrl = ref('');
@ -32,19 +44,49 @@ const app = {
const label = ref('');
const value = ref('');
// 提交pv的操作
/**
* 提交 pv
* @description 支持两种推送方式
*/
const pv = () => {
proxy.$pushBAIDU.pv(pageUrl.value);
// 通过钩子去操作
baidu.pv(pageUrl.value);
// 也可以通过全局属性去操作
// instance.appContext.config.globalProperties.$pushBAIDU.pv(pageUrl.value);
// 也可以通过代理组件去操作
// proxy.$pushBAIDU.pv(pageUrl.value);
}
// 提交事件的操作
/**
* 提交事件
* @description 支持两种推送方式
*/
const event = () => {
proxy.$pushBAIDU.event(
// 通过钩子去操作
baidu.event(
category.value,
action.value,
label.value,
value.value
);
// 也可以通过全局属性去操作
// instance.appContext.config.globalProperties.$pushBAIDU.event(
// category.value,
// action.value,
// label.value,
// value.value
// );
// 也可以通过代理组件去操作
// proxy.$pushBAIDU.event(
// category.value,
// action.value,
// label.value,
// value.value
// );
}
// Vue 3.0 需要把模板要用到的东西 return 出去
@ -64,7 +106,7 @@ const app = {
};
/**
/**
* 初始化Vue
*/
createApp(app)
@ -72,15 +114,14 @@ createApp(app)
.use(router)
// 启动插件
.use(baiduAnalytics, {
.use(baiduAnalytics.default, {
router: router,
siteIdList: [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc'
'bbbbbbbbbbbbbbbbbbb'
],
isDebug: true
})
// 挂载到节点上
.mount('#app');
.mount('#app');

View File

@ -4,9 +4,9 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[Vue2] vue baidu analytics demo</title>
<script src="https://unpkg.com/vue@2"></script>
<script src="https://unpkg.com/vue-router@3"></script>
<link rel="stylesheet" href="css/style.css">
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-router@3"></script>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
@ -59,8 +59,8 @@
</div>
<script src="../dist/vue-baidu-analytics.js"></script>
<script src="js/routes.js"></script>
<script src="js/main-for-vue2.js"></script>
<script src="./js/routes.js"></script>
<script src="./js/main-for-vue2.js"></script>
</body>
</html>
</html>

View File

@ -4,9 +4,9 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[Vue3] vue baidu analytics demo</title>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<link rel="stylesheet" href="css/style.css">
<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-router@4"></script>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
@ -59,8 +59,8 @@
</div>
<script src="../dist/vue-baidu-analytics.js"></script>
<script src="js/routes.js"></script>
<script src="js/main-for-vue3.js"></script>
<script src="./js/routes.js"></script>
<script src="./js/main-for-vue3.js"></script>
</body>
</html>
</html>

26
dist/main.d.ts vendored
View File

@ -1 +1,25 @@
export default function install(Vue: Vue, { router, siteIdList, isDebug }: Partial<Options>): boolean;
import type { Options, Vue } from '@/types'
/**
* Hooks
* @description Vue 3.0 使
* @example
* import { usePush } from 'vue-baidu-analytics'
* const baidu = usePush();
* baidu.pv('/');
*/
export declare function usePush(): {
pv: (pageUrl: string) => void
event: (
category: string,
action: string,
label: string,
value: number
) => void
}
/**
*
*/
export default function install(
Vue: Vue,
{ router, siteIdList, isDebug }: Partial<Options>
): void

View File

@ -1,10 +1,26 @@
/**
*
* https://tongji.baidu.com/open/api/more?p=guide_overview
*/
declare class BAIDU {
siteId: string;
isDebug: boolean;
constructor(siteId?: string, isDebug?: boolean);
/**
*
*/
init(): void;
/**
*
*/
setAccount(): void;
/**
* PVUV
*/
trackPageview(pageUrl: string): void;
trackEvent(category: string, action: string, label: string, value: number): boolean;
/**
*
*/
trackEvent(category: string, action: string, label: string, value: number): void;
}
export default BAIDU;

View File

@ -1,2 +1,7 @@
declare const getVueVersion: (Vue: Vue) => number;
export default getVueVersion;
import type { Vue } from '@/types'
/**
* Vue的版本
* @return 2=Vue2.x, 3=Vue3.x
*/
declare const getVueVersion: (Vue: Vue) => number
export default getVueVersion

View File

@ -1,9 +1,21 @@
/**
*
*/
declare class PushBAIDU {
siteIdList: string[];
isDebug: boolean;
constructor(siteIdList: string[], isDebug: boolean);
/**
*
*/
init(): void;
/**
* pv上报
*/
pv(pageUrl: string): void;
/**
*
*/
event(category: string, action: string, label: string, value: number): void;
}
export default PushBAIDU;

12
dist/types.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
import PushBAIDU from '@m/pushBAIDU'
export interface Options {
router: any
siteIdList: string[]
isDebug: boolean
}
export interface Vue {
prototype: any
$pushBAIDU: PushBAIDU
version: number | string
config: any
}

View File

@ -1,140 +1,297 @@
/**
/*!
* name: vue-baidu-analytics
* version: v2.0.0
* version: v2.2.0
* author: chengpeiquan
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.baiduAnalytics = factory());
}(this, (function () { 'use strict';
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? factory(exports)
: typeof define === 'function' && define.amd
? define(['exports'], factory)
: ((global =
typeof globalThis !== 'undefined' ? globalThis : global || self),
factory((global.baiduAnalytics = {})))
})(this, function (exports) {
'use strict'
var BAIDU = (function () {
function BAIDU(siteId, isDebug) {
if (siteId === void 0) { siteId = ''; }
if (isDebug === void 0) { isDebug = false; }
this.siteId = siteId;
this.isDebug = isDebug;
}
BAIDU.prototype.init = function () {
window._hmt = window._hmt ? window._hmt : [];
var SCRIPT = document.createElement('script');
SCRIPT['async'] = true;
SCRIPT['src'] = "https://hm.baidu.com/hm.js?" + this.siteId;
document.querySelector('head').appendChild(SCRIPT);
if (this.isDebug) {
console.log("[vue-baidu-analytics] siteId load done.\nsiteId: " + this.siteId);
}
};
BAIDU.prototype.setAccount = function () {
window._hmt.push(['_setAccount', this.siteId]);
};
BAIDU.prototype.trackPageview = function (pageUrl) {
if (!pageUrl || typeof pageUrl !== 'string') {
pageUrl = '/';
}
if (pageUrl.includes('http')) {
var PAGE_CUT = pageUrl.split('/');
var HOST_NAME = PAGE_CUT[0] + "//" + PAGE_CUT[2];
pageUrl = pageUrl.replace(HOST_NAME, '');
}
this.setAccount();
window._hmt.push(['_trackPageview', pageUrl]);
if (this.isDebug) {
console.log("[vue-baidu-analytics] track pv done.\nsiteId: " + this.siteId + "\npageUrl: " + pageUrl);
}
};
BAIDU.prototype.trackEvent = function (category, action, label, value) {
if (typeof category !== 'string' || typeof action !== 'string' || !category || !action) {
throw new Error('[vue-baidu-analytics] Missing necessary category and operation information, and must be of type string.');
}
if (!label || typeof label !== 'string') {
label = '';
}
if (!Number(value)) {
value = 1;
}
this.setAccount();
window._hmt.push(['_trackEvent', category, action, label, value]);
if (this.isDebug) {
console.log("[vue-baidu-analytics] track event done.\nsiteId: " + this.siteId + "\ncategory: " + category + "\naction: " + action + "\nlabel: " + label + "\nvalue: " + value);
}
};
return BAIDU;
}());
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
var PushBAIDU = (function () {
function PushBAIDU(siteIdList, isDebug) {
this.siteIdList = siteIdList;
this.isDebug = isDebug;
}
PushBAIDU.prototype.init = function () {
var _this = this;
this.siteIdList.forEach(function (siteId) {
var SITE = new BAIDU(siteId, _this.isDebug);
SITE.init();
});
};
PushBAIDU.prototype.pv = function (pageUrl) {
var _this = this;
this.siteIdList.forEach(function (siteId) {
var SITE = new BAIDU(siteId, _this.isDebug);
SITE.trackPageview(pageUrl);
});
};
PushBAIDU.prototype.event = function (category, action, label, value) {
var _this = this;
this.siteIdList.forEach(function (siteId) {
var SITE = new BAIDU(siteId, _this.isDebug);
SITE.trackEvent(category, action, label, value);
});
};
return PushBAIDU;
}());
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
var getVueVersion = function (Vue) {
var version = 2;
var VUE_VERSION = String(Vue.version);
if (VUE_VERSION.slice(0, 2) === '2.') {
version = 2;
}
if (VUE_VERSION.slice(0, 2) === '3.') {
version = 3;
}
return version;
};
function install(Vue, _a) {
var router = _a.router, siteIdList = _a.siteIdList, _b = _a.isDebug, isDebug = _b === void 0 ? false : _b;
if (typeof document === 'undefined' || typeof window === 'undefined') {
return false;
}
if (!router) {
throw new Error('[vue-baidu-analytics] Must pass a Vue-Router instance to vue-baidu-analytics.');
}
if (!siteIdList) {
throw new Error('[vue-baidu-analytics] Missing tracking domain ID, add at least one of baidu analytics.');
}
var pushBAIDU = new PushBAIDU(siteIdList, isDebug);
var VUE_VERSION = getVueVersion(Vue) || 2;
if (VUE_VERSION === 2) {
Vue.prototype.$pushBAIDU = pushBAIDU;
}
if (VUE_VERSION === 3) {
Vue.config.globalProperties.$pushBAIDU = pushBAIDU;
}
if (siteIdList) {
pushBAIDU.init();
}
router.afterEach(function (to) {
var PAGE_PATH_DIR_COUNT = window.location.pathname.split('/').length;
var PAGE_PATH = window.location.pathname.split('/').slice(0, PAGE_PATH_DIR_COUNT - 1).join('/');
var PAGE_URL = router.mode === 'hash' ? PAGE_PATH + "/#" + to.fullPath : "" + PAGE_PATH + to.fullPath;
pushBAIDU.pv(PAGE_URL);
});
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i)
ar[i] = from[i]
}
}
return to.concat(ar || from)
}
return install;
/**
* 定义基础配置
* 官方文档 https://tongji.baidu.com/open/api/more?p=guide_overview
*/
var BAIDU = /** @class */ (function () {
function BAIDU(siteId, isDebug) {
if (siteId === void 0) {
siteId = ''
}
if (isDebug === void 0) {
isDebug = false
}
this.siteId = siteId
this.isDebug = isDebug
}
/**
* 初始化
*/
BAIDU.prototype.init = function () {
var _a
window._hmt = window._hmt ? window._hmt : []
var SCRIPT = document.createElement('script')
SCRIPT['async'] = true
SCRIPT['src'] = 'https://hm.baidu.com/hm.js?' + this.siteId
;(_a = document.querySelector('head')) === null || _a === void 0
? void 0
: _a.appendChild(SCRIPT)
if (this.isDebug) {
console.log(
'[vue-baidu-analytics] siteId load done.\nsiteId: ' + this.siteId
)
}
}
/**
* 设置要响应的站点
*/
BAIDU.prototype.setAccount = function () {
window._hmt.push(['_setAccount', this.siteId])
}
/**
* 提交PVUV
*/
BAIDU.prototype.trackPageview = function (pageUrl) {
// 如果页面链接没传或者无效链接,则默认为根域名
if (!pageUrl || typeof pageUrl !== 'string') {
pageUrl = '/'
}
// 如果页面链接带上了域名,则需要过滤掉
if (pageUrl.startsWith('http')) {
var PAGE_CUT = pageUrl.split('/')
var HOST_NAME = PAGE_CUT[0] + '//' + PAGE_CUT[2]
pageUrl = pageUrl.replace(HOST_NAME, '')
}
// 设置响应 id 并提交数据
this.setAccount()
window._hmt.push(['_trackPageview', pageUrl])
if (this.isDebug) {
console.log(
'[vue-baidu-analytics] track pv done.\nsiteId: ' +
this.siteId +
'\npageUrl: ' +
pageUrl
)
}
}
/**
* 提交点击事件
*/
BAIDU.prototype.trackEvent = function (category, action, label, value) {
// 前两个是必填项
if (
typeof category !== 'string' ||
typeof action !== 'string' ||
!category ||
!action
) {
throw new Error(
'[vue-baidu-analytics] Missing necessary category and operation information, and must be of type string.'
)
}
// 重置一些无效的默认值
if (!label || typeof label !== 'string') {
label = ''
}
if (!Number(value)) {
value = 1
}
// 设置响应id并提交数据
this.setAccount()
window._hmt.push(['_trackEvent', category, action, label, value])
if (this.isDebug) {
console.log(
'[vue-baidu-analytics] track event done.\nsiteId: ' +
this.siteId +
'\ncategory: ' +
category +
'\naction: ' +
action +
'\nlabel: ' +
label +
'\nvalue: ' +
value
)
}
}
return BAIDU
})()
})));
/**
* 定义推送操作
*/
var PushBAIDU = /** @class */ (function () {
function PushBAIDU(siteIdList, isDebug) {
this.siteIdList = __spreadArray([], siteIdList)
this.isDebug = isDebug
}
/**
* 批量部署站点
*/
PushBAIDU.prototype.init = function () {
var _this = this
this.siteIdList.forEach(function (siteId) {
var SITE = new BAIDU(siteId, _this.isDebug)
SITE.init()
})
}
/**
* 批量提交pv上报
*/
PushBAIDU.prototype.pv = function (pageUrl) {
var _this = this
this.siteIdList.forEach(function (siteId) {
var SITE = new BAIDU(siteId, _this.isDebug)
SITE.trackPageview(pageUrl)
})
}
/**
* 批量提交事件上报
*/
PushBAIDU.prototype.event = function (category, action, label, value) {
var _this = this
this.siteIdList.forEach(function (siteId) {
var SITE = new BAIDU(siteId, _this.isDebug)
SITE.trackEvent(category, action, label, value)
})
}
return PushBAIDU
})()
/**
* 获取Vue的版本
* @return 2=Vue2.x, 3=Vue3.x
*/
var getVueVersion = function (Vue) {
var version = 2
// 获取Vue的版本号
var VUE_VERSION = String(Vue.version)
// Vue 2.x
if (VUE_VERSION.slice(0, 2) === '2.') {
version = 2
}
// Vue 3.x
if (VUE_VERSION.slice(0, 2) === '3.') {
version = 3
}
return version
}
/**
* 全局的数据
*/
var __GLOBAL__ = {
pushBAIDU: {},
}
/**
* 暴露 Hooks
* @description 解决 Vue 3.0 使用全局变量很麻烦的问题
* @example
* import { usePush } from 'vue-baidu-analytics'
* const baidu = usePush();
* baidu.pv('/');
*/
function usePush() {
// 提交 pv
function pv(pageUrl) {
return __GLOBAL__.pushBAIDU.pv(pageUrl)
}
// 提交事件
function event(category, action, label, value) {
return __GLOBAL__.pushBAIDU.event(category, action, label, value)
}
return {
pv: pv,
event: event,
}
}
/**
* 定义插件
*/
function install(Vue, _a) {
var router = _a.router,
siteIdList = _a.siteIdList,
_b = _a.isDebug,
isDebug = _b === void 0 ? false : _b
/**
* 一些环境和参数的检查
*/
if (typeof document === 'undefined' || typeof window === 'undefined') return
if (!siteIdList) {
throw new Error(
'[vue-baidu-analytics] Missing tracking domain ID, add at least one of baidu analytics siteId.'
)
}
/**
* 挂载推送的方法
*/
var pushBAIDU = new PushBAIDU(siteIdList, isDebug)
__GLOBAL__.pushBAIDU = pushBAIDU
/**
* 挂载全局变量到 Vue
* 获取Vue版本获取失败则默认为2
*/
var VUE_VERSION = getVueVersion(Vue) || 2
switch (VUE_VERSION) {
case 2:
Vue.prototype.$pushBAIDU = pushBAIDU
break
case 3:
Vue.config.globalProperties.$pushBAIDU = pushBAIDU
break
}
/**
* 部署站点并初始化
*/
if (siteIdList && Array.isArray(siteIdList)) {
pushBAIDU.init()
}
/**
* 路由切换时执行PV上报
*/
if (router) {
router.afterEach(function () {
// 获取要上报的链接(当前版本不需要拼接了)
var PAGE_URL = window.location.href
// 上报数据
pushBAIDU.pv(PAGE_URL)
})
}
}
exports.default = install
exports.usePush = usePush
Object.defineProperty(exports, '__esModule', { value: true })
})
//# sourceMappingURL=vue-baidu-analytics.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,172 @@
/**
/*!
* name: vue-baidu-analytics
* version: v2.0.0
* version: v2.2.0
* author: chengpeiquan
*/
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t="undefined"!=typeof globalThis?globalThis:t||self).baiduAnalytics=i()}(this,(function(){"use strict";var t=function(){function t(t,i){void 0===t&&(t=""),void 0===i&&(i=!1),this.siteId=t,this.isDebug=i}return t.prototype.init=function(){window._hmt=window._hmt?window._hmt:[];var t=document.createElement("script");t.async=!0,t.src="https://hm.baidu.com/hm.js?"+this.siteId,document.querySelector("head").appendChild(t),this.isDebug&&console.log("[vue-baidu-analytics] siteId load done.\nsiteId: "+this.siteId)},t.prototype.setAccount=function(){window._hmt.push(["_setAccount",this.siteId])},t.prototype.trackPageview=function(t){if(t&&"string"==typeof t||(t="/"),t.includes("http")){var i=t.split("/"),e=i[0]+"//"+i[2];t=t.replace(e,"")}this.setAccount(),window._hmt.push(["_trackPageview",t]),this.isDebug&&console.log("[vue-baidu-analytics] track pv done.\nsiteId: "+this.siteId+"\npageUrl: "+t)},t.prototype.trackEvent=function(t,i,e,n){if("string"!=typeof t||"string"!=typeof i||!t||!i)throw new Error("[vue-baidu-analytics] Missing necessary category and operation information, and must be of type string.");e&&"string"==typeof e||(e=""),Number(n)||(n=1),this.setAccount(),window._hmt.push(["_trackEvent",t,i,e,n]),this.isDebug&&console.log("[vue-baidu-analytics] track event done.\nsiteId: "+this.siteId+"\ncategory: "+t+"\naction: "+i+"\nlabel: "+e+"\nvalue: "+n)},t}(),i=function(){function i(t,i){this.siteIdList=t,this.isDebug=i}return i.prototype.init=function(){var i=this;this.siteIdList.forEach((function(e){new t(e,i.isDebug).init()}))},i.prototype.pv=function(i){var e=this;this.siteIdList.forEach((function(n){new t(n,e.isDebug).trackPageview(i)}))},i.prototype.event=function(i,e,n,o){var s=this;this.siteIdList.forEach((function(a){new t(a,s.isDebug).trackEvent(i,e,n,o)}))},i}();return function(t,e){var n=e.router,o=e.siteIdList,s=e.isDebug,a=void 0!==s&&s;if("undefined"==typeof document||"undefined"==typeof window)return!1;if(!n)throw new Error("[vue-baidu-analytics] Must pass a Vue-Router instance to vue-baidu-analytics.");if(!o)throw new Error("[vue-baidu-analytics] Missing tracking domain ID, add at least one of baidu analytics.");var r=new i(o,a),u=function(t){var i=2,e=String(t.version);return"2."===e.slice(0,2)&&(i=2),"3."===e.slice(0,2)&&(i=3),i}(t)||2;2===u&&(t.prototype.$pushBAIDU=r),3===u&&(t.config.globalProperties.$pushBAIDU=r),o&&r.init(),n.afterEach((function(t){var i=window.location.pathname.split("/").length,e=window.location.pathname.split("/").slice(0,i-1).join("/"),o="hash"===n.mode?e+"/#"+t.fullPath:""+e+t.fullPath;r.pv(o)}))}}));
!(function (t, e) {
'object' == typeof exports && 'undefined' != typeof module
? e(exports)
: 'function' == typeof define && define.amd
? define(['exports'], e)
: e(
((t =
'undefined' != typeof globalThis
? globalThis
: t || self).baiduAnalytics = {})
)
})(this, function (t) {
'use strict'
var e = (function () {
function t(t, e) {
void 0 === t && (t = ''),
void 0 === e && (e = !1),
(this.siteId = t),
(this.isDebug = e)
}
return (
(t.prototype.init = function () {
var t
window._hmt = window._hmt ? window._hmt : []
var e = document.createElement('script')
;(e.async = !0),
(e.src = 'https://hm.baidu.com/hm.js?' + this.siteId),
null === (t = document.querySelector('head')) ||
void 0 === t ||
t.appendChild(e),
this.isDebug &&
console.log(
'[vue-baidu-analytics] siteId load done.\nsiteId: ' +
this.siteId
)
}),
(t.prototype.setAccount = function () {
window._hmt.push(['_setAccount', this.siteId])
}),
(t.prototype.trackPageview = function (t) {
if (
((t && 'string' == typeof t) || (t = '/'), t.startsWith('http'))
) {
var e = t.split('/'),
i = e[0] + '//' + e[2]
t = t.replace(i, '')
}
this.setAccount(),
window._hmt.push(['_trackPageview', t]),
this.isDebug &&
console.log(
'[vue-baidu-analytics] track pv done.\nsiteId: ' +
this.siteId +
'\npageUrl: ' +
t
)
}),
(t.prototype.trackEvent = function (t, e, i, n) {
if ('string' != typeof t || 'string' != typeof e || !t || !e)
throw new Error(
'[vue-baidu-analytics] Missing necessary category and operation information, and must be of type string.'
)
;(i && 'string' == typeof i) || (i = ''),
Number(n) || (n = 1),
this.setAccount(),
window._hmt.push(['_trackEvent', t, e, i, n]),
this.isDebug &&
console.log(
'[vue-baidu-analytics] track event done.\nsiteId: ' +
this.siteId +
'\ncategory: ' +
t +
'\naction: ' +
e +
'\nlabel: ' +
i +
'\nvalue: ' +
n
)
}),
t
)
})(),
i = (function () {
function t(t, e) {
;(this.siteIdList = (function (t, e, i) {
if (i || 2 === arguments.length)
for (var n, o = 0, s = e.length; o < s; o++)
(!n && o in e) ||
(n || (n = Array.prototype.slice.call(e, 0, o)), (n[o] = e[o]))
return t.concat(n || e)
})([], t)),
(this.isDebug = e)
}
return (
(t.prototype.init = function () {
var t = this
this.siteIdList.forEach(function (i) {
new e(i, t.isDebug).init()
})
}),
(t.prototype.pv = function (t) {
var i = this
this.siteIdList.forEach(function (n) {
new e(n, i.isDebug).trackPageview(t)
})
}),
(t.prototype.event = function (t, i, n, o) {
var s = this
this.siteIdList.forEach(function (r) {
new e(r, s.isDebug).trackEvent(t, i, n, o)
})
}),
t
)
})(),
n = { pushBAIDU: {} }
;(t.default = function (t, e) {
var o = e.router,
s = e.siteIdList,
r = e.isDebug,
a = void 0 !== r && r
if ('undefined' != typeof document && 'undefined' != typeof window) {
if (!s)
throw new Error(
'[vue-baidu-analytics] Missing tracking domain ID, add at least one of baidu analytics siteId.'
)
var u = new i(s, a)
switch (
((n.pushBAIDU = u),
(function (t) {
var e = 2,
i = String(t.version)
return (
'2.' === i.slice(0, 2) && (e = 2),
'3.' === i.slice(0, 2) && (e = 3),
e
)
})(t) || 2)
) {
case 2:
t.prototype.$pushBAIDU = u
break
case 3:
t.config.globalProperties.$pushBAIDU = u
}
s && Array.isArray(s) && u.init(),
o &&
o.afterEach(function () {
var t = window.location.href
u.pv(t)
})
}
}),
(t.usePush = function () {
return {
pv: function (t) {
return n.pushBAIDU.pv(t)
},
event: function (t, e, i, o) {
return n.pushBAIDU.event(t, e, i, o)
},
}
}),
Object.defineProperty(t, '__esModule', { value: !0 })
})
//# sourceMappingURL=vue-baidu-analytics.min.js.map

File diff suppressed because one or more lines are too long

2061
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +1,34 @@
{
"name": "vue-baidu-analytics",
"version": "2.0.0",
"description": "A data collection tool that supports reporting of single-page application data built by Vue 3.0 & 2.0, based on baidu statistics.",
"version": "2.2.0",
"description": "A data collection tool that supports reporting of single-page application data built by Vue 3.0 & 2.0 & VuePress, based on baidu statistics.",
"main": "dist/vue-baidu-analytics.min.js",
"types": "vue-baidu-analytics.d.ts",
"scripts": {
"build": "rollup -c rollup.config.ts"
"build": "rollup -c rollup.config.ts",
"lint": "eslint src --ext .js,.ts",
"prettier": "prettier --write src"
},
"repository": {
"type": "git",
"url": "git+https://github.com/chengpeiquan/vue-baidu-analytics.git"
"url": "git+https://github.com/analyticsjs/vue-baidu-analytics.git"
},
"keywords": [
"baidu",
"vue baidu",
"vue 百度统计",
"vue analytics",
"vuepress analytics",
"vue 3.0 baidu",
"vue 3.0 百度统计",
"vue 3.0 analytics",
"spa 3.0 analytics",
"spa analytics",
"baidu统计",
"vuepress统计",
"百度统计"
],
"author": "chengpeiquan",
"homepage": "https://github.com/analyticsjs/vue-baidu-analytics",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.11.1",
@ -35,12 +40,33 @@
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"@types/babel__core": "^7.1.9",
"rollup": "^2.26.4",
"rollup-plugin-banner": "^0.2.1",
"rollup-plugin-banner2": "^1.0.0",
"@typescript-eslint/eslint-plugin": "^4.20.0",
"@typescript-eslint/parser": "^4.20.0",
"chalk": "^4.1.1",
"eslint": "^7.23.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"husky": "4.2.3",
"lint-staged": "^11.0.0",
"prettier": "^2.3.1",
"rollup": "^2.44.0",
"rollup-plugin-banner2": "^1.2.2",
"rollup-plugin-terser": "^7.0.0",
"rollup-plugin-typescript2": "^0.27.2",
"tslib": "^2.0.1",
"rollup-plugin-typescript2": "^0.30.0",
"tslib": "^2.3.0",
"typescript": "^4.0.2"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "node scripts/verifyCommit.js"
}
},
"lint-staged": {
"*.{js,jsx,vue,ts,tsx}": [
"prettier --write",
"eslint --fix",
"git add"
]
}
}

View File

@ -7,14 +7,12 @@ import banner2 from 'rollup-plugin-banner2'
import typescript from 'rollup-plugin-typescript2'
import pkg from './package.json'
// 版权信息配置
const ResolveBanner = () => {
return `/**
* name: ${pkg.name}
* version: v${pkg.version}
* author: ${pkg.author}
*/
`;
// 输出选项
const outputOptions = {
format: 'umd',
name: 'baiduAnalytics',
exports: 'named',
sourcemap: true
}
export default {
@ -22,32 +20,31 @@ export default {
output: [
{
file: `dist/vue-baidu-analytics.js`,
format: 'umd',
name: 'baiduAnalytics',
sourcemap: true
...outputOptions
},
{
file: `dist/vue-baidu-analytics.min.js`,
format: 'umd',
name: 'baiduAnalytics',
plugins: [
terser()
],
sourcemap: true
...outputOptions
}
],
plugins: [
resolve({
browser: true
}),
babel({
babelHelpers: 'bundled'
}),
commonjs(),
json(),
typescript(),
banner2( ResolveBanner, {
sourcemap: true
})
banner2(() => `/*!\n * name: ${pkg.name}\n * version: v${pkg.version}\n * author: ${pkg.author}\n */\n`)
]
};

27
scripts/verifyCommit.js Normal file
View File

@ -0,0 +1,27 @@
// Invoked on the commit-msg git hook by yorkie.
const fs = require('fs')
const chalk = require('chalk')
const msgPath = process.env.HUSKY_GIT_PARAMS
const msg = fs.readFileSync(msgPath, 'utf-8').trim()
const commitRE =
/^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/
if (!commitRE.test(msg)) {
console.log()
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
`invalid commit message format.`
)}\n\n` +
chalk.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
) +
` ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
` ${chalk.green(
`fix(v-model): handle events on blur (close #28)`
)}\n\n` +
chalk.red(` See .github/commit-convention.md for more details.\n`)
)
process.exit(1)
}

22
src/global.d.ts vendored
View File

@ -1,24 +1,8 @@
import PushBAIDU from '@m/pushBAIDU'
/* eslint-disable no-unused-vars */
export {}
declare global {
interface Window {
_hmt: any
}
interface Options {
router: any
siteIdList: string[]
isDebug: boolean
}
interface Vue {
prototype: any
$pushBAIDU: PushBAIDU
version: number | string
config: any
}
interface To {
fullPath: string
}
}
}

View File

@ -1,59 +1,100 @@
import PushBAIDU from '@m/pushBAIDU'
import getVueVersion from '@m/getVueVersion'
import type { Options, Vue } from '@/types'
/**
/**
*
*/
const __GLOBAL__ = {
pushBAIDU: {} as PushBAIDU,
}
/**
* Hooks
* @description Vue 3.0 使
* @example
* import { usePush } from 'vue-baidu-analytics'
* const baidu = usePush();
* baidu.pv('/');
*/
export function usePush() {
// 提交 pv
function pv(pageUrl: string) {
return __GLOBAL__.pushBAIDU.pv(pageUrl)
}
// 提交事件
function event(
category: string,
action: string,
label: string,
value: number
) {
return __GLOBAL__.pushBAIDU.event(category, action, label, value)
}
return {
pv,
event,
}
}
/**
*
*/
export default function install (Vue: Vue, { router, siteIdList, isDebug = false }: Partial<Options>) {
/**
export default function install(
Vue: Vue,
{ router, siteIdList, isDebug = false }: Partial<Options>
) {
/**
*
*/
if ( typeof document === 'undefined' || typeof window === 'undefined' ) {
return false;
if (typeof document === 'undefined' || typeof window === 'undefined') return
if (!siteIdList) {
throw new Error(
'[vue-baidu-analytics] Missing tracking domain ID, add at least one of baidu analytics siteId.'
)
}
if ( !router ) {
throw new Error('[vue-baidu-analytics] Must pass a Vue-Router instance to vue-baidu-analytics.');
}
if ( !siteIdList ) {
throw new Error('[vue-baidu-analytics] Missing tracking domain ID, add at least one of baidu analytics.');
}
/**
/**
*
*/
const pushBAIDU: any = new PushBAIDU(siteIdList, isDebug);
// 获取Vue版本获取失败则默认为2
const VUE_VERSION: number = getVueVersion(Vue) || 2;
const pushBAIDU: PushBAIDU = new PushBAIDU(siteIdList, isDebug)
__GLOBAL__.pushBAIDU = pushBAIDU
// 2.x可以直接挂载到原型上
if ( VUE_VERSION === 2 ) {
Vue.prototype.$pushBAIDU = pushBAIDU;
/**
* Vue
* Vue版本2
*/
const VUE_VERSION: number = getVueVersion(Vue) || 2
switch (VUE_VERSION) {
case 2:
Vue.prototype.$pushBAIDU = pushBAIDU
break
case 3:
Vue.config.globalProperties.$pushBAIDU = pushBAIDU
break
}
// 3.x必须使用这个方式来挂载
if ( VUE_VERSION === 3 ) {
Vue.config.globalProperties.$pushBAIDU = pushBAIDU;
}
/**
/**
*
*/
if ( siteIdList ) {
pushBAIDU.init();
if (siteIdList && Array.isArray(siteIdList)) {
pushBAIDU.init()
}
/**
/**
* PV上报
* @description v2.2.0
*/
router.afterEach( (to: To) => {
const PAGE_PATH_DIR_COUNT = window.location.pathname.split('/').length;
const PAGE_PATH = window.location.pathname.split('/').slice(0, PAGE_PATH_DIR_COUNT - 1).join('/');
const PAGE_URL = router.mode === 'hash' ? `${PAGE_PATH}/#${to.fullPath}` : `${PAGE_PATH}${to.fullPath}`;
if (router) {
router.afterEach(() => {
// 获取要上报的链接(当前版本不需要拼接了)
const PAGE_URL: string = window.location.href
pushBAIDU.pv(PAGE_URL);
});
}
// 上报数据
pushBAIDU.pv(PAGE_URL)
})
}
}

View File

@ -1,90 +1,102 @@
/**
/**
*
* https://tongji.baidu.com/open/api/more?p=guide_overview
*/
class BAIDU {
siteId: string;
isDebug: boolean;
siteId: string
isDebug: boolean
constructor (siteId: string = '', isDebug: boolean = false) {
this.siteId = siteId;
this.isDebug = isDebug;
constructor(siteId: string = '', isDebug: boolean = false) {
this.siteId = siteId
this.isDebug = isDebug
}
/**
/**
*
*/
init () {
window._hmt = window._hmt ? window._hmt : [];
const SCRIPT = document.createElement('script');
SCRIPT['async'] = true;
SCRIPT['src'] = `https://hm.baidu.com/hm.js?${this.siteId}`;
document.querySelector('head').appendChild(SCRIPT);
init() {
window._hmt = window._hmt ? window._hmt : []
const SCRIPT = document.createElement('script')
SCRIPT['async'] = true
SCRIPT['src'] = `https://hm.baidu.com/hm.js?${this.siteId}`
document.querySelector('head')?.appendChild(SCRIPT)
if ( this.isDebug ) {
console.log(`[vue-baidu-analytics] siteId load done.\nsiteId: ${this.siteId}`);
if (this.isDebug) {
console.log(
`[vue-baidu-analytics] siteId load done.\nsiteId: ${this.siteId}`
)
}
}
/**
/**
*
*/
setAccount () {
window._hmt.push(['_setAccount', this.siteId]);
setAccount() {
window._hmt.push(['_setAccount', this.siteId])
}
/**
/**
* PVUV
*/
trackPageview (pageUrl: string) {
trackPageview(pageUrl: string) {
// 如果页面链接没传或者无效链接,则默认为根域名
if ( !pageUrl || typeof pageUrl !== 'string' ) {
pageUrl = '/';
if (!pageUrl || typeof pageUrl !== 'string') {
pageUrl = '/'
}
// 如果页面链接带上了域名,则需要过滤掉
if ( pageUrl.includes('http') ) {
const PAGE_CUT = pageUrl.split('/');
const HOST_NAME = `${PAGE_CUT[0]}//${PAGE_CUT[2]}`;
pageUrl = pageUrl.replace(HOST_NAME, '');
if (pageUrl.startsWith('http')) {
const PAGE_CUT = pageUrl.split('/')
const HOST_NAME = `${PAGE_CUT[0]}//${PAGE_CUT[2]}`
pageUrl = pageUrl.replace(HOST_NAME, '')
}
// 设置响应id并提交数据
this.setAccount();
window._hmt.push(['_trackPageview', pageUrl]);
// 设置响应 id 并提交数据
this.setAccount()
window._hmt.push(['_trackPageview', pageUrl])
if ( this.isDebug ) {
console.log(`[vue-baidu-analytics] track pv done.\nsiteId: ${this.siteId}\npageUrl: ${pageUrl}`);
if (this.isDebug) {
console.log(
`[vue-baidu-analytics] track pv done.\nsiteId: ${this.siteId}\npageUrl: ${pageUrl}`
)
}
}
/**
/**
*
*/
trackEvent (category: string, action: string, label: string, value: number) {
trackEvent(category: string, action: string, label: string, value: number) {
// 前两个是必填项
if ( typeof category !== 'string' || typeof action !== 'string' || !category || !action ) {
throw new Error('[vue-baidu-analytics] Missing necessary category and operation information, and must be of type string.');
return false;
if (
typeof category !== 'string' ||
typeof action !== 'string' ||
!category ||
!action
) {
throw new Error(
'[vue-baidu-analytics] Missing necessary category and operation information, and must be of type string.'
)
}
// 重置一些无效的默认值
if ( !label || typeof label !== 'string' ) {
label = '';
if (!label || typeof label !== 'string') {
label = ''
}
if ( !Number(value) ) {
value = 1;
if (!Number(value)) {
value = 1
}
// 设置响应id并提交数据
this.setAccount();
window._hmt.push(['_trackEvent', category, action, label, value]);
this.setAccount()
window._hmt.push(['_trackEvent', category, action, label, value])
if ( this.isDebug ) {
console.log(`[vue-baidu-analytics] track event done.\nsiteId: ${this.siteId}\ncategory: ${category}\naction: ${action}\nlabel: ${label}\nvalue: ${value}`);
if (this.isDebug) {
console.log(
`[vue-baidu-analytics] track event done.\nsiteId: ${this.siteId}\ncategory: ${category}\naction: ${action}\nlabel: ${label}\nvalue: ${value}`
)
}
}
}
export default BAIDU;
export default BAIDU

View File

@ -1,24 +1,26 @@
/**
* Vue的版本
* @return 2=Vue2.x, 3=Vue3.x
*/
const getVueVersion = (Vue: Vue): number => {
let version: number = 2;
// 获取Vue的版本号
const VUE_VERSION: string = String(Vue.version);
// Vue 2.x
if ( VUE_VERSION.slice(0, 2) === '2.' ) {
version = 2;
}
// Vue 3.x
if ( VUE_VERSION.slice(0, 2) === '3.' ) {
version = 3;
}
return version;
}
export default getVueVersion;
import type { Vue } from '@/types'
/**
* Vue的版本
* @return 2=Vue2.x, 3=Vue3.x
*/
const getVueVersion = (Vue: Vue): number => {
let version: number = 2
// 获取Vue的版本号
const VUE_VERSION: string = String(Vue.version)
// Vue 2.x
if (VUE_VERSION.slice(0, 2) === '2.') {
version = 2
}
// Vue 3.x
if (VUE_VERSION.slice(0, 2) === '3.') {
version = 3
}
return version
}
export default getVueVersion

View File

@ -1,47 +1,46 @@
import BAIDU from '@m/baidu'
/**
/**
*
*/
class PushBAIDU {
siteIdList: string[];
isDebug: boolean;
siteIdList: string[]
isDebug: boolean
constructor (siteIdList: string[], isDebug: boolean) {
this.siteIdList = siteIdList;
this.isDebug = isDebug;
constructor(siteIdList: string[], isDebug: boolean) {
this.siteIdList = [...siteIdList]
this.isDebug = isDebug
}
/**
/**
*
*/
init () {
this.siteIdList.forEach( (siteId: string) => {
const SITE = new BAIDU(siteId, this.isDebug);
SITE.init();
});
init() {
this.siteIdList.forEach((siteId: string) => {
const SITE = new BAIDU(siteId, this.isDebug)
SITE.init()
})
}
/**
/**
* pv上报
*/
pv (pageUrl: string) {
this.siteIdList.forEach( (siteId: string) => {
const SITE = new BAIDU(siteId, this.isDebug);
SITE.trackPageview(pageUrl);
});
pv(pageUrl: string) {
this.siteIdList.forEach((siteId: string) => {
const SITE = new BAIDU(siteId, this.isDebug)
SITE.trackPageview(pageUrl)
})
}
/**
/**
*
*/
event (category: string, action: string, label: string, value: number) {
this.siteIdList.forEach( (siteId: string) => {
const SITE = new BAIDU(siteId, this.isDebug);
SITE.trackEvent(category, action, label, value);
});
event(category: string, action: string, label: string, value: number) {
this.siteIdList.forEach((siteId: string) => {
const SITE = new BAIDU(siteId, this.isDebug)
SITE.trackEvent(category, action, label, value)
})
}
}
export default PushBAIDU;
export default PushBAIDU

14
src/types.ts Normal file
View File

@ -0,0 +1,14 @@
import PushBAIDU from '@m/pushBAIDU'
export interface Options {
router: any
siteIdList: string[]
isDebug: boolean
}
export interface Vue {
prototype: any
$pushBAIDU: PushBAIDU
version: number | string
config: any
}

View File

@ -2,11 +2,15 @@
"compilerOptions": {
"target": "ES5",
"module": "ES2015",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"strictNullChecks": true,
"baseUrl": ".",
"paths": {
"@/*": [

2969
yarn.lock Normal file

File diff suppressed because it is too large Load Diff