vuex中使用provide / inject组合刷新页面
本文档主要参考【坏小哥】的Vue刷新页面的三种方式的文档
1、在RouterView【命令视图】组件,也就是App.vue组件中通过provide来提供变量
<template>
<div id="app">
<router-view v-if="isRouterAlive"></router-view>
</div>
</template>
<script>
// Vuex 辅助函数的导入
import { mapState, mapMutations } from "vuex";
export default {
name: "App",
provide() {
//父组件中通过provide来提供变量,在子组件中通过inject来注入变量。
return {
reload: this.reload,
};
},
computed: {
...mapState({
// 获取isRouterAlive,模块化后开启命名空间模块方法
isRouterAlive: (state) => state.app.isRouterAlive,
}),
},
methods: {
...mapMutations({
reload: "app/RELOAD",
}),
},
};
</script>
2、在app.vue的模块化js文件中执行reload方法
const state = {
isRouterAlive: true, //控制视图是否显示的变量
}
const mutations = {
RELOAD(state) {
state.isRouterAlive = false; //先关闭,
Vue.nextTick(function () {
state.isRouterAlive = true; //再打开
});
}
}
3、在需要刷新页面的组件中注入App里的reload方法
4、在需要刷新页面的代码块中调用reload()方法
1)先获取所有组件的方法
组件中的代码
created() {
// 获取store所有数据
this.getAllData();
},
methods: {
...mapActions({
// 获取store所有数据
getAllData:"template/getAllData",
}),
}
该组件vuex中的代码
const state = {
rootCommit: {},
}
const actions = {
getAllData(store) {
const { commit, dispatch, state, rootState, getters, rootGetters } = store
state.rootCommit = commit
}
}
2)调用app组件的reload()方法
state.rootCommit('app/RELOAD', {}, { root: true })
上面代码表示,当前模块中调用其他模块的mutations的方法:
参数1 => 调用方法
参数2 => 传递的参数,如没有参数可传,写{}
参数3 => 表示是否是其他模块的方法