Vue重载组件(常用)
activated
/ inject
-
activated()/deactivated()
当我们想要在进入一个组件和离开这个组件时执行一些方法的时候,如果这个组件被<keep-alive />
包裹,就可以使用这两个钩子函数,activated在组件一被加载时调用,deactivated在一离开组件是调用。配合
v-if
使用可以实现组件的重载,在页面进入时设为true
离开时再设为false
<baidu-map
v-if="mapReload" />
activated() {
// 进入activate组件时
this.mapReload = true
this.doSomething()
},
deactivated() {
// 离开activate组件时
this.mapReload = false
this.doSomething()
},
provide/inject
当我们想在任何时候刷新这个页面时,例如当ajax请求完成时需要重载页面以获得更新,如果用location.reload()
体验感会很差,相当于用户刷新了这个页面。而采用provide/inject
这种方式原理是将<router-view/>
先隐藏再显示,达到重新渲染路由区域的效果,体验感极好
// 首先需要在 App.vue中
<router-view v-if="isRouterAlive" />
// <script>
provide() {
return {
reload: this.reload
}
},
data() {
return {
isRouterAlive: true
}
},
methods: {
reload() {
this.isRouterAlive = false
this.$nextTick(() => {
this.isRouterAlive = true
})
}
}
// 之后在任何页面都可以通过依赖注入的方式引入this.reload方法直接调用
// <script>
inject: ['reload'],
data() {
return {
}
}
method() {
this.$get('path').then(res => {
this.reload()
})
}