【发布时间】:2020-11-03 18:37:28
【问题描述】:
我使用vuex,在我的页面模块中我设置了标题和内容,我安排了一个销毁的方法来重置它们,如果我点击不同的组件,重置值时没有问题但是当我点击不同的静态页面时,组件不会被破坏,数据也不会更新。有没有办法为同一个组件重置 vuex 状态值?
const state = {
page: {},
};
const getters = {
page(state) {
return state.page;
},
};
const mutations = {
setAPage (state, pPage) {
state.page = pPage
state.errors = {}
},
setCleanPage(state){
state.page = null
},
reset(state) {
const s = state();
Object.keys(s).forEach(key => {
state[key] = s[key];
});
console.log('state', state)
}
}
const actions = {
fetchAPage (context, payload) {
context.commit("setCleanPage");
const {slug} = payload;
return ApiService.get(`pages/${slug}/`)
.then((data) => {
context.commit("setAPage", data.data);
})
.catch((response) => {
context.commit("setError", response.data)
})
},
resetAPage(context){
context.commit("reset");
}
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
在我的组件中:
<script>
import { mapGetters, mapActions, mapMutations } from "vuex";
export default {
name: "Page",
computed: {
...mapGetters('pages', {page: 'page'}),
},
beforeRouteLeave (to, from, next) {
// called when the route that renders this component has changed,
// but this component is reused in the new route.
// For example, for a route with dynamic params /foo/:id, when we
// navigate between /foo/1 and /foo/2, the same Foo component instance
// will be reused, and this hook will be called when that happens.
// has access to >this component instance.
console.log(to)
console.log(from)
console.log(next)
this.$store.dispatch('pages/resetAPage');
},
methods: {
...mapActions(['pages/fetchAPage']),
},
destroyed() {
this.toggleBodyClass('removeClass', 'landing-page');
this.$store.dispatch('pages/resetAPage');
},
created() {
this.$store.dispatch('pages/fetchAPage' , this.$route.params)
},
};
</script>
如何重置或更新同一组件的数据?
谢谢
【问题讨论】:
-
你应该检查你是否真的有一个名为
resetAPage的突变——或者它实际上只是reset -
是的,我有,在缩短我的代码时忘记添加它,我现在添加。
-
是否可以在导航链接上使用@onclick 编写函数?我想到了这个想法,但我不确定这是个好主意还是坏主意。
-
您可以使用
beforeRouteLeave守卫(router.vuejs.org/guide/advanced/…)