Vue的項目中,如果項目簡單, 父子組件之間的數(shù)據(jù)傳遞可以使用 props 或者 $emit 等方式 進行傳遞
但是如果是大中型項目中,很多時候都需要在不相關的平行組件之間傳遞數(shù)據(jù),并且很多數(shù)據(jù)需要多個組件循環(huán)使用。這時候再使用上面的方法會讓項目代碼變得冗長,并且不利于組件的復用,提高了耦合度。
Vue 的狀態(tài)管理工具 Vuex 完美的解決了這個問題。
看了下vuex的官網(wǎng),覺得不是很好理解,有的時候我們只是需要動態(tài)的從一個組件中獲取數(shù)據(jù)(官網(wǎng)稱為“組件層級”:是個獨立的控件,作用范圍只在組件之內(nèi))然后想放到一個被官網(wǎng)稱作“應用層級”(在項目的任意地方都可以隨時獲取和動態(tài)的修改,在修改之后,vue會為你的整個項目做更新)的地方。這是我最初來學習vue的原因,我并不想做一個前端數(shù)據(jù)結構庫。。
下面看看我一步一步的小例子
首先安裝vuex 目前公司項目已經(jīng)被我從vue1.0遷移到vue2.0,下載并安裝vue
npm install vuex --save
然后在index.html同級新建文件夾store,在文件夾內(nèi)新建index.js文件,這個文件我們用來組裝模塊并導出 store 的文件
【一、獲取store中的數(shù)據(jù)】
import Vue from 'vue' import Vuex from 'vuex' // 告訴 vue “使用” vuex Vue.use(Vuex) // 創(chuàng)建一個對象來保存應用啟動時的初始狀態(tài) // 需要維護的狀態(tài) const store = new Vuex.Store({ state: { // 放置初始狀態(tài) app啟動的時候的全局的初始值 bankInf: {"name":"我是vuex的第一個數(shù)據(jù)","id":100,"bankName":"中國銀行"} } }) // 整合初始狀態(tài)和變更函數(shù),我們就得到了我們所需的 store // 至此,這個 store 就可以連接到我們的應用中 export default store
在vue根文件中注冊store,這樣所有的組件都可以使用store中的數(shù)據(jù)了
我的項目文件結構:
在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中的數(shù)據(jù),使用方法也很簡單,就是使用計算屬性返回store中的數(shù)據(jù)到一個新屬性上,然后在你模板中則可以使用這個屬性值了:
任意組件中:
export default { ... computed: { bankName() { return this.$store.state.bankInf.bankName; } }, ... }
在模板中可以直接使用bankName這個屬性了,也就是store中的中國銀行
【二、在組件中修改store中的狀態(tài) 】
在任意組件中添加html模板
<div class="bank"> <list-header :headerData="bankName"></list-header> 04銀行詳情頁面 <input name="" v-model="textValue"> <button type="button" name="獲取數(shù)據(jù)" @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: { // 放置初始狀態(tài) app啟動的時候的全局的初始值 bankInf: {"name":"我是vuex的第一個數(shù)據(jù)","id":100,"bankName":"中國銀行"}, count:0 }, mutations: { newBankName(state,msg) { state.bankInf.bankName = msg; } } })
這樣你發(fā)現(xiàn),在點擊提交按鈕的時候,頁面已經(jīng)顯示你修改的數(shù)據(jù)了,并且所有復用這個組件的地方的數(shù)據(jù)全都被vue更新了;
如果在使用中發(fā)現(xiàn)報錯this.$store.commit is not a function ,請打開你項目的配置文件package.json,查看你正在使用的vuex的版本,我正在使用的是vuex2.0,
如果想刪除舊版本的vuex并安裝新版本的vuex請使用
npm rm vuex --save
然后安裝最新的vuex
npm install vuex --save
即可解決這個錯誤,或者是查看vuex官網(wǎng)api修改提交mutation的語句
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com