有很多更干净的方法可以做到这一点。
首先,如果您使用 Nuxt,那么,在我看来,您应该使用它的出色功能中间件 https://nuxtjs.org/guide/routing#middleware用于分派操作(在组件级别不保留它的用例)。
其次,Vuex为我们提供了mapGetters
该功能使状态属性在组件中可用,同时保持它们的反应性。
因此,您可以采用以下方法:
Vuex 商店:
export const state = () => ({
section: 0,
notifications: ["notification 1", "notification 2", "notification 3"]
});
export const mutations = {
INC_SECTION(state) {
state.section++;
},
RESET_SECTION(state) {
state.section = 0;
}
};
export const actions = {
rotate({ commit, dispatch, state }) {
setTimeout(() => {
let total = state.notifications.length - 1;
if (state.section === total) {
commit("RESET_SECTION");
} else {
commit("INC_SECTION");
}
dispatch("rotate");
}, 3500);
}
};
export const getters = {
notifications(state) {
return state.notifications;
},
section(state) {
return state.section;
}
};
export default {
state,
mutations,
actions,
getters
};
Vue 组件:
<template>
<section class="notifications">
<template v-for="(notification, i) in notifications">
<p v-if="section === i" :key="i">{{ notification }}</p>
</template>
</section>
</template>
<script>
import { mapGetters } from "vuex";
export default {
data() {
return {};
},
computed: {
...mapGetters(["notifications", "section"])
}
};
</script>
中间件
export default function({ store }) {
store.dispatch("rotate");
}
根据您的用例,您可以将此中间件保持全局(附加到路由),或附加到特定布局。
这是一个工作sandbox https://codesandbox.io/s/yjw28pkpjz例子。希望这能帮助你。