Vue.js實戰之Vuex的入門教程


在 Vue.js 的項目中,如果項目結構簡單, 父子組件之間的數據傳遞可以使用  props 或者 $emit 等方式。

但是如果是大型項目,很多時候都需要在子組件之間傳遞數據,使用之前的方式就不太方便。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: '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,可以讓我們更好的跟蹤每一個狀態的變化,所以在大型項目中,更推薦使用第二種方法。

 

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助。

來源:http://www.cnblogs.com/wisewrong/p/6344390.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM