Vue的項目中,如果項目簡單, 父子組件之間的數據傳遞可以使用 props 或者 $emit 等方式 進行傳遞
但是如果是大中型項目中,很多時候都需要在不相關的平行組件之間傳遞數據,並且很多數據需要多個組件循環使用。這時候再使用上面的方法會讓項目代碼變得冗長,並且不利於組件的復用,提高了耦合度。
Vue 的狀態管理工具 Vuex 完美的解決了這個問題。
看了下vuex的官網,覺得不是很好理解,有的時候我們只是需要動態的從一個組件中獲取數據(官網稱為“組件層級”:是個獨立的控件,作用范圍只在組件之內)然后想放到一個被官網稱作“應用層級”(在項目的任意地方都可以隨時獲取和動態的修改,在修改之后,vue會為你的整個項目做更新)的地方。這是我最初來學習vue的原因,我並不想做一個前端數據結構庫。。。
下面看看我一步一步的小例子
首先安裝vuex 目前公司項目已經被我從vue1.0遷移到vue2.0,下載並安裝vue
npm install vuex --save
然后在index.html同級新建文件夾store,在文件夾內新建index.js文件,這個文件我們用來組裝模塊並導出 store 的文件
【一、獲取store中的數據】
1 import Vue from 'vue'
2 import Vuex from 'vuex'
3
4 // 告訴 vue “使用” vuex
5 Vue.use(Vuex) 6
7 // 創建一個對象來保存應用啟動時的初始狀態
8 // 需要維護的狀態
9 const store = new Vuex.Store({ 10 state: { 11 // 放置初始狀態 app啟動的時候的全局的初始值
12 bankInf: {"name":"我是vuex的第一個數據","id":100,"bankName":"中國銀行"} 13 } 14 }) 15 // 整合初始狀態和變更函數,我們就得到了我們所需的 store
16 // 至此,這個 store 就可以連接到我們的應用中
17 export default store
在vue根文件中注冊store,這樣所有的組件都可以使用store中的數據了
我的項目文件結構:
在main.js文件中注冊store
1 import Vue from 'vue'
2 import App from './App'
3 import router from './router'
4 import store from './../store/index'
5
6 /* eslint-disable no-new */
7 new Vue({ 8 el: '#app', 9 router, 10 store, 11 template: '<App/>', 12 components: { App } 13 })
這樣簡單的第一步就完成了,你可以再任意組件中使用store中的數據,使用方法也很簡單,就是使用計算屬性返回store中的數據到一個新屬性上,然后在你模板中則可以使用這個屬性值了:
任意組件中:
1 export default { 2 ... 3 computed: { 4 bankName() { 5 return this.$store.state.bankInf.bankName; 6 } 7 }, 8 ... 9 }
在模板中可以直接使用bankName這個屬性了,也就是store中的中國銀行
【二、在組件中修改store中的狀態 】
在任意組件中添加html模板
1 <div class="bank">
2 <list-header :headerData="bankName"></list-header>
3 04銀行詳情頁面 4 <input name="" v-model="textValue">
5 <button type="button" name="獲取數據" @click="newBankName"></button>
6 </div>
然后組件中提交mutation
1 export default { 2 ... 3 computed: { 4 bankName() { 5 return this.$store.state.bankInf.bankName; 6 } 7 }, 8 methods: { 9 newBankName: function() { 10 this.$store.commit('newBankName', this.textValue) 11 } 12 } 13 ... 14 }
在store中的index.js中添加mutations:
1 const store = new Vuex.Store({ 2 state: { 3 // 放置初始狀態 app啟動的時候的全局的初始值
4 bankInf: {"name":"我是vuex的第一個數據","id":100,"bankName":"中國銀行"}, 5 count:0
6 }, 7 mutations: { 8 newBankName(state,msg) { 9 state.bankInf.bankName = msg; 10 } 11 } 12 })
這樣你發現,在點擊提交按鈕的時候,頁面已經顯示你修改的數據了,並且所有復用這個組件的地方的數據全都被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的語句
原文地址: https://blog.csdn.net/jingtian678/article/details/81481075