使用this.$store.commit 需要提前在store中写变量吗
时间: 2024-03-04 19:29:30 浏览: 16
是的,使用this.$store.commit需要提前在store中定义对应的变量。在Vuex中,store包含了应用的状态(state)和操作状态的方法(mutations)。当你想要改变状态时,需要提交(commit)一个mutation。mutation是Vuex中改变状态的唯一合法方式,每个mutation都有一个字符串类型的事件类型和一个回调函数,回调函数的第一个参数是当前的state对象。你可以在mutations中定义变量,并在组件中调用this.$store.commit来触发对应的mutation,从而改变相应的状态。
相关问题
methods: { logout() { this.$store.commit("removeToken"); }, },解释this.$store
this.$store 是 Vue.js 中的一个全局变量,用于访问 Vuex 状态管理库中的 store 对象。Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。因此,this.$store.commit("removeToken") 表示调用 Vuex 中名为 removeToken 的 mutation 方法,从而移除应用程序中的 token。
count的值怎么不显示 <template> <div> <h3>当前最新的count值为:{{ count }}</h3> <button @click="btnHandler1">+1</button> <button @click="btnHandler2">+N</button> <button @click="btnHandler3">+1 Async</button> <button @click="btnHandler4">+N Async</button> </div> </template> <script> // import {mapState} from 'vuex' export default { data(){ return{ count:'' } },methods:{ btnHandler1(){ this.$store.commit('add') }, btnHandler2(){ this.$store.commit('addN',3) }, btnHandler3(){ this.$store.dispatch('addAsync') }, btnHandler4(){ this.$store.dispatch('addNAsync',3) } } } </script>
count 的值可能不显示是因为当前组件没有引用 vuex 中的 state 中的 count 变量。可以尝试在组件中引入 Vuex 的 mapState 辅助函数,然后在模板中使用该函数映射 state 中的 count 变量,如下所示:
<template>
<div>
<h3>当前最新的count值为:{{ count }}</h3>
<button @click="btnHandler1">1</button>
<button @click="btnHandler2">N</button>
<button @click="btnHandler3">1 Async</button>
<button @click="btnHandler4">N Async</button>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
btnHandler1() {
this.$store.commit('add');
},
btnHandler2() {
this.$store.commit('addN', 3);
},
btnHandler3() {
this.$store.dispatch('addAsync');
},
btnHandler4() {
this.$store.dispatch('addNAsync', 3);
},
},
};
</script>