wx.config和wx.agentconfig是所有其它接口成功调用的前提。uni-app的onLaunch是应用初始化完成后调用,全局只触发一次,适合调用wx.config和wx.agentconfig。各页面的onLoad监听页面加载。onLaunch会在onLoad之前调用,但由于wx.config和wx.agentconfig是异步调用,执行结果的顺序就无法保证。如果在onLoad中调用了微信接口,就可能出现undefined(可能是config没执行完)或no permission(可能是agentconfig没执行完)错误。
解决方法:
使用vuex的状态监听,在wx.config和wx.agentconfig都成功执行后设置状态;同时在页面监听状态,当发现状态变更后再触发接口调用。
//main.js
Vue.use(Vuex)
Vue.prototype.$store = new Vuex.Store({
state: {
ready: false
},
mutations: {
setReady (state) {
state.ready = true
}
}
})
// App.vue
wx.config({
...
})
wx.ready(
function() {
wx.agentConfig({
...
success: function(res) {
that.$store.commit('setReady')
}
})
}
)
// page.vue
computed: {
isReady() {
return this.$store.state.ready
}
},
watch: {
isReady(newVal, oldVal) {
if(newVal) {
// call wx.api here
}
}
}