全局监听是否调用了隐私api
使用webpack打包的方式将 监听组件
打包到每个页面
使用vue-inset-loader
实现此效果
如果是使用Hbuild创建的项目没有vue.config.js
需要自己手动创建一个vue.config.js
使用webpack打包的目的是将隐私弹窗全局引入到每个页面中
wx.onNeedPrivacyAuthorization是全局监听
安装
npm install vue-inset-loader --save-dev
在vue.config.js
中插入以下代码
const path = require('path');
module.exports = {
configureWebpack: {
module: {
rules: [
{
test: /\.vue$/,
use: {
loader: path.resolve(__dirname, './node_modules/vue-inset-loader')
}
}
]
}
}
}
在pages.json
中插入以下代码
"insetLoader": {
"config": {
"privacy": "<privacy-monitoring></privacy-monitoring>"
},
"label": ["privacy-monitoring"],
"rootEle": "view"
},
在main.js
中插入以下代码
import PrivacyMonitoring from '@/components/privacy-monitoring.vue';
Vue.component('privacy-monitoring', PrivacyMonitoringfrom);
privacy-monitoring.vue
<template>
<!-- 自己写UI -->
<button id="disagree" @click="disagree">不同意</button>
<button id="agree" open-type="agreePrivacyAuthorization" @agreeprivacyauthorization="agree">同意并继续</button>
</template>
<script>
export default {
data() {
return {
operate: new Set() // 存放监听回调方法 使用Set避免存放重复的回调
};
},
created() {
// 监听是否调用了隐私api
wx.onNeedPrivacyAuthorization(resolve => {
this.handler(resolve);
});
},
methods: {
handler(resolve) {
wx.getPrivacySetting({
success: (result) => {
// 是否需要用户授权隐私协议
if (result.needAuthorization) {
this.operate.add(resolve); // 将监听api的回调存入operate
}
}
});
},
agree() {
// 这里循环调用存放的回调
// 执行存放的回调会重新触发隐私api
// 无需用户再次触发
this.operate.forEach(resolve => {
resolve({
event: 'agree', // 同意
buttonId: 'agree' // 同意按钮的ID
});
});
this.operate.clear(); // 清空存放的回调
},
disagree() {
this.operate.forEach(resolve => {
resolve({
event: 'disagree', // 不同意
buttonId: 'disagree' // 不同意按钮的ID
});
});
this.operate.clear(); // 清空存放的回调
},
}
}
</script>