代碼示例:
this.$store.commit('loginStatus', 1);
this.$store.dispatch('isLogin', true)
規範的使用方式:
// 以載荷形式
store.commit('increment',{
amount: 10 //這是額外的參數
})
// 或者使用對象風格的提交方式
store.commit({
type: 'increment',
amount: 10 //這是額外的參數
-
})
主要區別:
dispatch:含有異步操作,數據提交至 actions ,可用於向後臺提交數據
寫法示例:
this.$store.dispatch('isLogin', true);
commit:同步操作,數據提交至 mutations ,可用於登錄成功後讀取用戶信息寫到緩存裏
寫法示例:
this.$store.commit('loginStatus', 1);
兩者都可以以載荷形式或者對象風格的方式進行提交。
//登錄成功後讀取用戶信息寫到緩存裏demo submitForm(form){ window.localStorage.clear(); this.$refs[form].validate((valid) => { if (valid) { var loginData = {}; let $this = this; const that = this; axios.get('/login', {username: this.loginForm.username, password: this.loginForm.password}) .then(function (res) { if (res.status == 200) { setStore('token', res.data.token); setStore('roleCode', res.data.roleCode); store.commit(types.ROLECODE, {roleCode: res.data.roleCode}); setStore('username', that.loginForm.username); store.commit(types.LOGIN, {token: res.data.token}); setStore('permissions', res.data.permissions); store.commit(types.PERMISSIONS, {permissions: res.data.permissions}); $this.$router.push('/home'); } else { consol.log(error); } }) .catch(function (error) { console.log(error); }); } else { Message.error('登錄失敗'); return false; } }); },