vuex 漸進(jìn)式教程,從入門級(jí)帶你慢慢深入使用vuex。
Vuex 是什么?
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài), 并以相應(yīng) 的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。
vuex官網(wǎng): vuex.vuejs.org/zh/guide/
安裝
安裝vue-cli:
cnpm install -g vue-cli vue init webpack vuex
安裝vuex
	cnpm i vuex --save
1.初級(jí)使用方法
// main.jsimport Vue from 'vue'import App from './App'import router from './router'import Vuex from 'vuex' // 引入vuexVue.config.productionTip = falseVue.use(Vuex);let store = new Vuex.Store({ // store 對(duì)象 state:{  count:0 }})/* eslint-disable no-new */new Vue({ el: '#app', router, store, //使用store,這可以把 store 的實(shí)例注入所有的子組件 components: { App }, template: '<App/>'})此時(shí)可以在組件中使用 this.$store.state.count 獲取store中state的值。如:
// 在組件的computed中使用 computed:{   count(){   return this.$store.state.count;   } }想想一下當(dāng)項(xiàng)目比較大的時(shí)候數(shù)據(jù)繁瑣,如果按照上述方法使用vuex,當(dāng)你打開main.js你看的到場景是比較混亂的,各種數(shù)據(jù)繁雜在一起,不便于日后的維護(hù)。請看下一步:
2.中級(jí)使用方法: modules 模塊化
state用法
2.1 在main.js中刪除下述這部分代碼
let store = new Vuex.Store({ // store 對(duì)象 state:{  count:0 }})2.2. 在src目錄下新建store文件夾并在該文件夾下新建index.js文件。 在 store/index.js寫入:
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({ strict:true, // 開啟嚴(yán)格模式 確保state 中的數(shù)據(jù)只能 mutations 修改 state:{  count:0 }})export default store;對(duì)應(yīng)的main.js應(yīng)該寫入:
	import store from './store'
寫到這里,我們在組件里就可以獲取到store里的state的值了
2.3 為了方便測試直接在HelloWorld.vue 中使用store
<template> <div class="hello">  <h2>{{count}}</h2> </div></template><script>export default { name: 'HelloWorld', computed:{   count(){    return this.$store.state.count;   } }}</script>很多時(shí)候咱們要對(duì)state里的值進(jìn)行操作,在vuex提供了一個(gè)方法mutations
mutations用法(使用mutations可以修改state的值)
在sore/index.js寫入:
//... state:{  count:0 }, mutations:{ // 更改數(shù)據(jù)的方法  add(state){   state.count++  },  //提交載荷用法//   add(state,n){ //   state.count += n//  },  sub(state){   state.count--  } }...//組件(HelloWorld.vue)中使用mutations里對(duì)應(yīng)的方法:
<template> <div class="hello">  <button @click="add">+</button>  <h2>{{count}}</h2>  <button @click="sub">-</button> </div></template><script>export default { name: 'HelloWorld', computed:{   count(){    return this.$store.state.count;   } },  methods:{  add(){   this.$store.commit('add');  },    //提交載荷用法  // add(){   //  this.$store.commit('add',10);  // },    //對(duì)象風(fēng)格的提交方式  //  store.commit({  //   type: 'add',  //   n: 10  //   })    sub(){   this.$store.commit('sub');  } }}</script>此時(shí)就可以對(duì)count進(jìn)行修改了。
當(dāng)你想異步操作的時(shí)候,由于mutation必須是同步的這一點(diǎn),此時(shí)不能采用mutation對(duì)state 進(jìn)行修改。action派上用場了,action就是一個(gè)函數(shù)集合,在里面怎么操作都可以,只要最后觸發(fā)mutation 就可以了。
注解mutation不能異步操作的原因:
mutations: {  add (state) {   api.callAsyncMethod(() => {  state.count++  }) }}現(xiàn)在想象,我們正在 debug 一個(gè) app 并且觀察 devtool 中的 mutation 日志。每一條 mutation 被記錄,devtools 都需要捕捉到前一狀態(tài)和后一狀態(tài)的快照。然而,在上面的例子中 mutation 中的異步函數(shù)中的回調(diào)讓這不可能完成:因?yàn)楫?dāng) mutation 觸發(fā)的時(shí)候,回調(diào)函數(shù)還沒有被調(diào)用,devtools 不知道什么時(shí)候回調(diào)函數(shù)實(shí)際上被調(diào)用——實(shí)質(zhì)上任何在回調(diào)函數(shù)中進(jìn)行的狀態(tài)的改變都是不可追蹤的。
Action 用法
在sore/index.js寫入:
 mutations:{ // 更改數(shù)據(jù)的方法add(state){   state.count++  },  sub(state){   state.count--  } },++++ actions:{  add(context){ // context 與 store 實(shí)例具有相同方法和屬性(但不是store 實(shí)例)   setTimeout(()=>{    context.commit('add');   },1000)  } }++++組件(HelloWorld.vue)中使用getters里對(duì)應(yīng)的方法:
<template> <div class="hello">  <button @click="add">+</button>  ++++  <button @click="add_action">action +</button>  ++++  <h2>{{count}}</h2>  <button @click="sub">-</button>  <div>   test: {{doneTodos[0].text}} <br>   length: {{doneTodosLength}}  </div> </div></template>export default { methods:{  add(){   this.$store.commit('add');   // console.log(this);  },  sub(){   this.$store.commit('sub');  },  ++++  add_action(){   this.$store.dispatch('add');  }  ++++ }}看到這里有沒有想過當(dāng)我們使用state中某一個(gè)數(shù)據(jù)時(shí),我們只想用該數(shù)據(jù)中符合條件的數(shù)據(jù)。比如:
state:{  count:0,  todos: [   { id: 1, text: 'text1--true', done: true },   { id: 2, text: 'text2--false', done: false }  ] }此時(shí)我們只想獲取state.todos中done為true的數(shù)據(jù)時(shí)我們應(yīng)該怎么獲取?
可能會(huì)有以下兩種方案:
1.每個(gè)在組件中首先獲取todos,然后使用filter方法過濾;
2.寫一個(gè)公共函數(shù)在每個(gè)組件中調(diào)用以下;
如果用到todos中done為true的組件很多,這兩種方法都是很不理想的。Vuex為此為我們引入了一個(gè)方法Getter。
Getter 用法
官方解釋:Vuex 允許我們在 store 中定義“getter”(可以認(rèn)為是 store 的計(jì)算屬性)。就像計(jì)算屬性一樣,getter 的返回值會(huì)根據(jù)它的依賴被緩存起來,且只有當(dāng)它的依賴值發(fā)生了改變才會(huì)被重新計(jì)算。
在sore/index.js寫入:
mutations:{ // 更改數(shù)據(jù)的方法  add(state){   state.count++  },  sub(state){   state.count--  } }, +++ getters:{ // 用法類似組件中的 computed, 可以認(rèn)為是store的計(jì)算屬性  doneTodos:state => { // Getter 接受 state 作為其第一個(gè)參數(shù):   return state.todos.filter(todo => todo.done) // -> [{ id: 1, text: 'text1--true', done: true }]  },  // Getter 也可以接受其他 getter 作為第二個(gè)參數(shù)  doneTodosLength:(state,getters) => {   return getters.doneTodos.length // -> 1  }, +++ }組件(HelloWorld.vue)中使用getters里對(duì)應(yīng)的方法:
<template> <div class="hello">  <button @click="add">+</button>  <h2>{{count}}</h2>  <button @click="sub">-</button>+++  <div>   test: {{doneTodos[0].text}} <br>   length: {{doneTodosLength}}  </div>+++   </div></template><script>export default { //...  computed:{  +++    doneTodos(){     return this.$store.getters.doneTodos // -> [{ id: 1, text: 'text1--true', done: true }]    },    doneTodosLength(){     return this.$store.getters.doneTodosLength // -> 1    }  +++ }}</script>本篇代碼地址: github.com/xioasa/vue-…
總結(jié)
以上所述是小編給大家介紹的vuex 漸進(jìn)式教程實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
新聞熱點(diǎn)
疑難解答