1. 程式人生 > >Vue 爬坑之路(四)—— 與 Vuex 的第一次接觸

Vue 爬坑之路(四)—— 與 Vuex 的第一次接觸

參數 之間 scrip span 變量 tle 技術分享 管理 tool

在 Vue.js 的項目中,如果項目結構簡單, 父子組件之間的數據傳遞可以使用 props 或者 $emit 等方式 http://www.cnblogs.com/wisewrong/p/6266038.html

但是如果是大型項目,很多時候都需要在子組件之間傳遞數據,使用之前的方式就不太方便。Vue 的狀態管理工具 Vuex 完美的解決了這個問題。

一、安裝並引入 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: ‘TIng‘
  }
})

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&nbsp;&copy;&nbsp;{{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,可以讓我們更好的跟蹤每一個狀態的變化,所以在大型項目中,更推薦使用第二種方法。

分類: Vue

Vue 爬坑之路(四)—— 與 Vuex 的第一次接觸