vuex中的this.$store.commit...
Vue的專案中,如果專案簡單, 父子元件之間的資料傳遞可以使用 props 或者 $emit 等方式 進行傳遞
但是如果是大中型專案中,很多時候都需要在不相關的平行元件之間傳遞資料,並且很多資料需要多個元件迴圈使用。這時候再使用上面的方法會讓專案程式碼變得冗長,並且不利於元件的複用,提高了耦合度。
Vue 的狀態管理工具 Vuex 完美的解決了這個問題。
下面看看我一步一步的小例子
首先安裝vuex 目前公司專案已經被我從vue1.0遷移到vue2.0,下載並安裝vue
npm install vuex --save
然後在index.html同級新建資料夾store,在資料夾內新建index.js檔案,這個檔案我們用來組裝模組並匯出 store 的檔案
【一、獲取store中的資料】
import Vue from 'vue' import Vuex from 'vuex' // 告訴 vue “使用” vuex Vue.use(Vuex) // 建立一個物件來儲存應用啟動時的初始狀態 // 需要維護的狀態 const store = new Vuex.Store({ state: { // 放置初始狀態 app啟動的時候的全域性的初始值 bankInf: {"name":"我是vuex的第一個資料","id":100,"bankName":"中國銀行"} } }) // 整合初始狀態和變更函式,我們就得到了我們所需的 store// 至此,這個 store 就可以連線到我們的應用中 export default store
在vue根檔案中註冊store,這樣所有的元件都可以使用store中的資料了,在main.js檔案中註冊store
import Vue from 'vue' import App from './App' import router from './router' import store from './../store/index' /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
這樣簡單的第一步就完成了,你可以再任意元件中使用store中的資料,使用方法也很簡單,就是使用計算屬性返回store中的資料到一個新屬性上,然後在你模板中則可以使用這個屬性值了:
export default { ... computed: { bankName() { return this.$store.state.bankInf.bankName; } }, ... }
在模板中可以直接使用bankName這個屬性了,也就是store中的中國銀行
【二、在元件中修改store中的狀態 】
在任意元件中新增html模組
<div class="bank">
<list-header :headerData="bankName"></list-header>
04銀行詳情頁面
<input name="" v-model="textValue">
<button type="button" name="獲取資料" @click="newBankName"></button>
</div>
然後元件中提交mutation
export default { ... computed: { bankName() { return this.$store.state.bankInf.bankName; } }, methods: { newBankName: function() { this.$store.commit('newBankName', this.textValue) } } ... }
在store中的index.js中新增mutations:
const store = new Vuex.Store({ state: { // 放置初始狀態 app啟動的時候的全域性的初始值 bankInf: {"name":"我是vuex的第一個資料","id":100,"bankName":"中國銀行"}, count:0 }, mutations: { newBankName(state,msg) { state.bankInf.bankName = msg; } } })
這樣你發現,在點選提交按鈕的時候,頁面已經顯示你修改的資料了,並且所有複用這個元件的地方的資料全都被vue更新了;
如果在使用中發現報錯this.$store.commit is not a function ,請開啟你專案的配置檔案package.json,檢視你正在使用的vuex的版本,我正在使用的是vuex2.0,
如果想刪除舊版本的vuex並安裝新版本的vuex請使用
npm rm vuex --save
然後安裝最新的vuex
npm install vuex --save
即可解決這個錯誤,或者是檢視vuex官網api修改提交mutation的語句