一、安裝並引入 Vuex
項目結構:
首先使用 npm 安裝 Vuex
cnpm install vuex -S
然後在 main.js 中引入
import Vue from 'vue'import App from './App'import Vuex from 'vuex'import store from './vuex/store'Vue.use(Vuex)/* eslint-disable no-new */
new Vue({ el: '#app', store, render: h => h(App)})
二、構建核心倉庫 store.js
Vuex 應用的狀態 state 都應當存放在 store.js 裡面,Vue 組件可以從 store.js 裡面擷取狀態,可以把 store 通俗的理解為一個全域變數的倉庫。
但是和單純的全域變數又有一些區別,主要體現在當 store 中的狀態發生改變時,相應的 vue 組件也會得到高效更新。
在 src 目錄下建立一個 vuex 目錄,將 store.js 放到 vuex 目錄下
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({ // 定義狀態 state: { author: 'Wise Wrong' }})export default store
這是一個最簡單的 store.js,裡面只存放一個狀態 author
雖然在 main.js 中已經引入了 Vue 和 Vuex,但是這裡還得再引入一次
三、將狀態映射到組件
<template> <footer class="footer"> <ul> <li v-for="lis in ul">{{lis.li}}</li> </ul> <p> Copyright © {{author}} - 2016 All rights reserved </p> </footer></template><script> export default { name: 'footerDiv', data () { return { ul: [ { li: '琉璃之金' }, { li: '朦朧之森' }, { li: '縹緲之滔' }, { li: '逍遙之火' }, { li: '璀璨之沙' } ] } }, computed: { author () { return this.$store.state.author } } }</script>
這是 footer.vue 的 html 和 script 部分
主要在 computed 中,將 this.$store.state.author 的值返回給 html 中的 author
頁面渲染之後,就能擷取到 author 的值
四、在組件中修改狀態
然後在 header.vue 中添加一個輸入框,將輸入框的值傳給 store.js 中的 author
這裡我使用了 Element-UI 作為樣式架構
上面將輸入框 input 的值綁定為 inputTxt,然後在後面的按鈕 button 上綁定 click 事件,觸發 setAuthor 方法
methods: { setAuthor: function () { this.$store.state.author = this.inpuTxt }}
在 setAuthor 方法中,將輸入框的值 inputTxt 賦給 Vuex 中的狀態 author,從而實現子組件之間的資料傳遞
五、官方推薦的修改狀態的方式
上面的樣本是在 setAuthor 直接使用賦值的方式修改狀態 author,但是 vue 官方推薦使用下面的方法:
首先在 store.js 中定義一個方法 newAuthor,其中第一個參數 state 就是 $store.state,第二個參數 msg 需要另外傳入
然後修改 header.vue 中的 setAuthor 方法
這裡使用 $store.commit 提交 newAuthor,並將 this.inputTxt 傳給 msg,從而修改 author
這樣顯式地提交(commit) mutations,可以讓我們更好的跟蹤每一個狀態的變化,所以在大型項目中,更推薦使用第二種方法。