基础知识
在 Vuex 中,this.$store.dispatch
方法用于向 store 发起一个mutation 事件。
Mutation 是改变 Vuex 存储状态的唯一方法。
以下是 this.$store.dispatch
方法的基本使用示例:
1.首先,确保你在 Vue 组件中已经引入了 Vuex:
import Vuex from 'vuex';
2.然后,在你的组件中使用 this.$store.dispatch
方法来触发一个Mutation:
// 假设你有一个名为 increment 的 Mutation
this.$store.dispatch('increment');
3.在你的 Vuex store 中定义这个 Mutation:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++;
}
}
});
通过以上步骤,你可以使用 this.$store.dispatch
方法来触发 increment
Mutation,从而递增 count
的值。
需要注意的是,this.$store.dispatch
方法需要一个字符串作为参数,这个字符串对应于你在 Vuex store 中定义的 Mutation 的名称。
另外,还可以通过传递一个对象作为第二个参数来传递 Mutation 的参数:
this.$store.dispatch('increment', 5);
这将把 5
作为 increment
Mutation 的参数传递给它。
知识储备
在 Vuex 中,需要使用 commit
方法来触发mutations
里的方法。
mutations
是用于改变 Vuex
存储状态的唯一方式。
以下是一个示例:
-
首先,确保你在 Vue 组件中已经引入了 Vuex:
import Vuex from 'vuex';
2. 然后,在你的组件中使用 `this.$store.commit` 方法来触发一个 Mutation:
```javascript
// 假设你有一个名为 SET_TOKEN 的 Mutation
this.$store.commit('SET_TOKEN', tokenV);
在这个示例中,SET_TOKEN
是你在 Vuex store 中定义的 Mutation 的名称,tokenV
是你要传递给Mutation 的参数。
-
最后,在你的 Vuex store 中定义这个 Mutation:
const store = new Vuex.Store({ state: { // 存储状态的地方 }, mutations: { // 定义 Mutation SET_TOKEN (state, token) { state.token = token; } } });
通过以上三个步骤,你可以使用 `this.$store.commit` 方法来触发 `SET_TOKEN` Mutation,从而在 store 中成功存储 `tokenV`。
需要注意的是,在使用 `commit` 方法时,确保传递正确的 Mutation 名称和参数。如果 Mutation 名称或参数不正确,或者没有在 store 中定义相应的 Mutation,那么存储操作可能会失败。
## 案例解析
[传送门](https://blog.csdn.net/lemonC77/article/details/95077691)
**main.js**
```js
new Vue({
router,
store,
i18n,
render: h => h(App),
}).$mount('#app')
store/index.js
在store/modules文件夹里的user.js,声明user并释放出来。
const user = {
state: {
token: '',
roles: null,
isMasterAccount:true,
},
mutations: {
SET_TOKEN: (state, token) => {
state.token ="Bearer " +token
},
},
actions: {
// 登录
Login({
commit
}, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo.account, userInfo.password).then(x => {
if(x.status==200){
const tokenV = x.data.token.tokenValue
commit('SET_TOKEN', tokenV)
document.cookie=`AuthInfo=Bearer ${tokenV};path:/`;
token="Bearer "+tokenV;
//setToken("Bearer " +token)
resolve();
}
}).catch(error => {
console.log("登录失败")
reject(error)
})
})
},
}
}
export default user
注:必须要用commit(‘SET_TOKEN’, tokenV)
调用mutations
里的方法,才能在store
存储成功。
handleLogin() {
this.loading = true
this.$store.dispatch('Login', this.loginForm).then(() => {
this.$router.push({
path: '/manage/merchant/account'
}); //登录成功之后重定向到首页
this.loading = false
// this.$router.push({ path: this.redirect || '/' })
}).catch(() => {
this.loading = false
})
}
this.$store.dispatch(‘Login’, this.loginForm)
来调取store
里的user.js的login
方法,从而要更新。