Vue 问题
watch 监听 $route 失效
在 vue 子组件中使用 watch 监听路由变化, 代码如下:
1 2 3 4 5 6 7 8 9 10 11
| watch: { '$route'(to, from) { window.scrollTo(0, 0) this.getWxShare(to.path) }, '$store.state.nickname'() { this.getWxShare() } }
|
需要把 watch 函数写在父组件里, 在父组件中监听内嵌路由, 比如放在 App.vue 里面可以监听整个路由的变化。
当使用路由参数时, 例如从 /user/foo 导航到 /user/bar , 原来的组件实例会被复用。 因为两个路由都渲染同个组件, 比起销毁再创建, 复用则显得更加高效。 不过, 这也意味着组件的生命周期钩子不会再被调用。 所以在某个组件中监听路由变化只能监听到该组件路由的子路由。
dispatch 某个 action 后同步执行另外一个方法
可以在 action 操作中 return 一个 promise , 当接口请求完成后 resolve() , 在组件中执行 dispatch 之后在 .then() 里执行后续操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| const actions = { getUserInfo({ commit }) { return new Promise(async (resolve, reject) => { let result = null await userInfo().then(res => { if (res.data.code == '1001') { result = res.data } else if (res.data.code == '1005') { window.location.href = loginUrl } else { Toast({ message: res.data.msg, position: 'bottom', duration: 2000 }) } }) commit('getUserInfo', result) resolve() }) } }
this.$store.dispatch('getUserInfo').then(() => { if (this.$store.state.isVip == 3) { this.getCountdown() } })
|