使用场景为增加商品表单,用户确定提交后,继续新增,需要清理之前用户输入数据,并对其初始化,再走一遍组件加载的流程,其中还包括几个子组件,如果手动去处理实在是太麻烦!! - 知乎提问
利用 v-if 控制 router-view,在路由容器组件,如 APP.vue 中实现一个刷新方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <template> <router-view v-if="isRouterAlive" /> </template> <script> export default { data() { return { isRouterAlive: true, } }, methods: { reload() { this.isRouterAlive = false this.$nextTick(() => (this.isRouterAlive = true)) }, }, } </script>
|
然后其它任何想刷新自己的路由页面,都可以这样:
如果$root 节点不是路由容器组件,可以使用 provide / inject 来传递 reload
路由容器组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <router-view v-if="isRouterAlive" /> </template> <script> export default { provide() { return { reload: this.reload, } }, data() { return { isRouterAlive: true, } }, methods: { reload() { this.isRouterAlive = false this.$nextTick(() => (this.isRouterAlive = true)) }, }, } </script>
|
子组件:
1 2 3 4 5
| { inject: ['reload'] } ... this.reload()
|
——— 更新 ———
再补充一下,其实基于上述原理,你可以封装一个 reload 组件,然后其他组件通过 Mixins 的方式再引入它,这样就可以很方便地支持任意组件级别的 reload 了