vue:vuex詳解

1、什麼是Vuex?javascript

https://vuex.vuejs.org/zh-cnhtml

官方說法:Vuex 是一個專爲 Vue.js應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。vue

我的理解:Vuex是用來管理組件之間通訊的一個插件java

2、爲何要用Vuex?git

咱們知道組件之間是獨立的,組件之間想要實現通訊,我目前知道的就只有props選項,但這也僅限於父組件和子組件之間的通訊。若是兄弟組件之間想要實現通訊呢?嗯..,方法應該有。拋開怎麼實現的問題,試想一下,當作中大型項目時,面對一大堆組件之間的通訊,還有一大堆的邏輯代碼,會不會很抓狂??那爲什麼不把組件之間共享的數據給「拎」出來,在必定的規則下管理這些數據呢? 這就是Vuex的基本思想了。ajax

3、Vuex有什麼特性?vuex

怎麼使用Vuex?chrome

引入Vuex.js文件 。vue-cli

建立實例:npm

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <script src="./js/vuex.js"></script> <script src="./js/vue2.0.js"></script> <body> <div id="app"> </div> </body> <script> Vue.use(Vuex);//在建立Vue實例以前 var myStore = new Vuex.Store({ state:{ //存放組件之間共享的數據 name:"jjk" }, mutations:{ //顯式的更改state裏的數據 }, getters:{ //獲取數據的方法 }, actions:{ // } }); new Vue({ el:"#app", data:{ name:"dk" }, store:myStore, mounted:function(){ console.log(this)//控制檯 } }) </script> </html>

先解釋上面代碼的意思:

new Vuex.Store({}) 表示建立一個Vuex實例,一般狀況下,他須要注入到Vue實例裏。Store是Vuex的一個核心方法,字面上理解爲「倉庫」的意思。Vuex Store是響應式的,當Vue組件從store中讀取狀態(state選項)時,若store中的狀態發生更新時,他會及時的響應給其餘的組件(相似雙向數據綁定) 並且不能直接改變store的狀態,改變狀態的惟一方法就是,顯式地提交更改(mutations選項)。

他有4個核心選項:state、mutations、getters、actions(下文會仔細分析)。

這是上面代碼:

 

那如何獲取到state的數據呢?

通常會在組件的計算屬性(computed)獲取state的數據(由於,計算屬性會監控數據變化,一旦發生改變就會響應)。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <script src="./js/vuex.js"></script> <script src="./js/vue2.0.js"></script> <body> <div id="app"> <hello></hello> </div> </body> <script> Vue.use(Vuex); var myStore = new Vuex.Store({ state:{ //存放組件之間共享的數據 name:"jjk" }, mutations:{ //顯式的更改state裏的數據 }, getters:{ //過濾state數據 }, actions:{ // } }); Vue.component('hello',{ template:"<p>{{name}}</p>", computed: { name:function(){ return this.$store.state.name } }, mounted:function(){ console.log(this) } }) new Vue({ el:"#app", data:{ name:"dk" }, store:myStore, mounted:function(){ console.log(this) } }) </script> </html>

在chrome中顯示:

 

state:用來存放組件之間共享的數據。他跟組件的data選項相似,只不過data選項是用來存放組件的私有數據。

getters:有時候,咱們須要對state的數據進行篩選,過濾。這些操做都是在組件的計算屬性進行的。若是多個組件須要用到篩選後的數據,那咱們就必須處處重複寫該計算屬性函數;或者將其提取到一個公共的工具函數中,並將公共函數多處導入 - 二者都不太理想。若是把數據篩選完在傳到計算屬性裏就不用那麼麻煩了,getters就是幹這個的,你能夠把getters當作是store的計算屬性。getters下的函數接收接收state做爲第一個參數。那麼,組件是如何獲取通過getters過濾的數據呢? 過濾的數據會存放到$store.getters對象中。具體看一個例子:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <script src="./js/vuex.js"></script> <script src="./js/vue2.0.js"></script> <body> <div id="app"> <hello></hello> </div> </body> <script> Vue.use(Vuex); var myStore = new Vuex.Store({ state:{ //存放組件之間共享的數據 name:"jjk", age:18 }, mutations:{ //顯式的更改state裏的數據 }, getters:{ getAge:function(state){ return state.age; } }, actions:{ // } }); Vue.component('hello',{ template:"<p>姓名:{{name}} 年齡:{{age}}</p>", computed: { name:function(){ return this.$store.state.name }, age:function(){ return this.$store.getters.getAge } }, mounted:function(){ console.log(this) } }) new Vue({ el:"#app", data:{ name:"dk" }, store:myStore, mounted:function(){ console.log(this) } }) </script> </html>

 

mutations:前面講到的都是如何獲取state的數據,那如何把數據存儲到state中呢?在 Vuex store 中,實際改變 狀態(state) 的惟一方式是經過 提交(commit) 一個 mutation。  

mutations下的函數接收state做爲參數,接收一個叫作payload(載荷)做爲第二個參數,這個參數是用來記錄開發者使用該函數的一些信息,好比說提交了什麼,提交的東西是用來幹什麼的,包含多個字段,因此載荷通常是對象(其實這個東西跟git的commit很相似)還有一點須要注意:mutations方法必須是同步方法!

具體看實例:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <script src="./js/vuex.js"></script> <script src="./js/vue2.0.js"></script> <body> <div id="app"> <hello></hello> </div> </body> <script> Vue.use(Vuex); var myStore = new Vuex.Store({ state:{ //存放組件之間共享的數據 name:"jjk", age:18, num:1 }, mutations:{ //顯式的更改state裏的數據 change:function(state,a){ // state.num++; console.log(state.num += a); } }, getters:{ getAge:function(state){ return state.age; } }, actions:{ // } }); Vue.component('hello',{ template:"<p @click='changeNum'>姓名:{{name}} 年齡:{{age}} 次數:{{num}}</p>", computed: { name:function(){ return this.$store.state.name }, age:function(){ return this.$store.getters.getAge }, num:function(){ return this.$store.state.num } }, mounted:function(){ console.log(this) }, methods: { changeNum: function(){ //在組件裏提交 // this.num++; this.$store.commit('change',10) } }, data:function(){ return { // num:5 } } }) new Vue({ el:"#app", data:{ name:"dk" }, store:myStore, mounted:function(){ console.log(this) } }) </script> </html>

當點擊p標籤前,chrome中顯示:

點擊p標籤後:

 

能夠看出,更改state的數據並顯示在組件中,有幾個步驟:

一、在mutations選項裏,註冊函數,函數裏面裝邏輯代碼;

二、在組件裏this.$store.commit('change',payload),注意:提交的函數名要一一對應 ;

三、觸發函數,state就會相應更改;

四、在組件的計算屬性裏使用this.$store.state 獲取你想要獲得的數據。

actions:既然mutations只能處理同步函數,我大js全靠‘異步回調’吃飯,怎麼能沒有異步,因而actions出現了...  

actions和mutations的區別:

一、Actions 提交的是 mutations,而不是直接變動狀態。也就是說,actions會經過mutations,讓mutations幫他提交數據的變動。

二、Action 能夠包含任意異步操做。ajax、setTimeout、setInterval不在話下

再來看一下實例:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <script src="./js/vuex.js"></script> <script src="./js/vue2.0.js"></script> <body> <div id="app"> <hello></hello> </div> </body> <script> Vue.use(Vuex); var myStore = new Vuex.Store({ state:{ //存放組件之間共享的數據 name:"jjk", age:18, num:1 }, mutations:{ //顯式的更改state裏的數據 change:function(state,a){ // state.num++; console.log(state.num += a); }, changeAsync:function(state,a){ console.log(state.num +=a); } }, getters:{ getAge:function(state){ return state.age; } }, actions:{         //設置延時 add:function(context,value){ setTimeout(function(){            //提交事件 context.commit('changeAsync',value); },1000) } } }); Vue.component('hello',{ template:` <div> <p @click='changeNum'>姓名:{{name}} 年齡:{{age}} 次數:{{num}}</p> <button @click='changeNumAnsyc'>change</button> </div>`, computed: { name:function(){ return this.$store.state.name }, age:function(){ return this.$store.getters.getAge }, num:function(){ return this.$store.state.num } }, mounted:function(){ console.log(this) }, methods: { changeNum: function(){ //在組件裏提交 // this.num++; this.$store.commit('change',10) },         //在組件裏派發事件 當點擊按鈕時,changeNumAnsyc觸發-->actions裏的add函數被觸發-->mutations裏的changeAsync函數觸發 changeNumAnsyc:function(){ this.$store.dispatch('add', 5); } }, data:function(){ return { // num:5 } } }) new Vue({ el:"#app", data:{ name:"dk" }, store:myStore, mounted:function(){ console.log(this) } }) </script> </html>

點擊按鈕一秒後,chrome中顯示:

 

先整明白 context dispatch是什麼東西:

context:context是與 store 實例具備相同方法和屬性的對象。能夠經過context.state和context.getters來獲取 state 和 getters。

dispatch:翻譯爲‘派發、派遣’的意思,觸發事件時,dispatch就會通知actions(跟commit同樣同樣的)參數跟commit也是同樣的。

action的大致流程:

1.在actions選項裏添加函數(異步)並提交到對應的函數(在mutation選項裏)中  context.commit('changeAsync',value);

actions:{
             add:function(context,value){ setTimeout(function(){ context.commit('changeAsync',value); },1000) } }

總結:

各個類型的 API各司其職,mutation 只管存,你給我(dispatch)我就存;action只管中間處理,處理完我就給你,你怎麼存我無論;Getter 我只管取,我不改的;action放在了 methods 裏面,說明咱們應該把它當成函數來用(講道理,鉤子函數也應該能夠的) ;mutation是寫在store裏面的,這說明,它就是個半成品,中間量,咱們不該該在外面去操做它;getter寫在了 computed 裏面,這說明雖然 getter咱們寫的是函數,可是咱們應該把它當成計算屬性來用。

4、在vue文件中怎麼使用?

假如你使用的是vue-cli,若是vue-cli中沒有安裝vuex,則在cmd中定位到你項目所在的目錄安裝vuex:

cnpm install vuex --save

在src目錄下新建一個vuex文件夾,文件夾下創建一個store.js文件:

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { title: '新聞', content: '今天有什麼重要新聞呢?', count: 10 } const getters = { run: function(state){ if (state.count > 5){ state.count = 0; } else { return '小於5'; } } } const mutations = { btn () { alert(1); } } export default new Vuex.Store({ state, getters, mutations }) 

在vue文件(和vuex同級目錄的components目錄下)中使用:

<template>
  <div>
    <p>Vuex的使用方式2:{{title}}</p>
    <p>Vuex的content值爲:{{count}}</p>
    <p>Vuex中getters的用法:{{run}}</p>
    <div><button @click="btn">Alert</button></div>
  </div>
</template>

<script>
import store from '../store'
import {mapState, mapGetters, mapMutations} from 'vuex'
export default {
  store,
  computed: {
    ...mapState(['title', 'count']),
    ...mapGetters(['run'])
  },
  name: 'users',
  methods: {
    ...mapMutations(['btn'])
  }
}
</script>

<style scoped="">

</style>

5、Vuex使用詳解:

在SPA單頁面組件的開發中 Vue的vuex和React的Redux 都統稱爲同一狀態管理,我的的理解是全局狀態管理更合適;簡單的理解就是你在state中定義了一個數據以後,你能夠在所在項目中的任何一個組件裏進行獲取、進行修改,而且你的修改能夠獲得全局的響應變動。下面我們一步一步地剖析下vuex的使用:

首先要安裝、使用 vuex

首先在 vue 2.0+ 你的vue-cli項目中安裝 vuex:

npm install vuex --save

而後 在src文件目錄下新建一個名爲store的文件夾,爲方便引入並在store文件夾裏新建一個index.js,裏面的內容以下:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store(); export default store;

接下來,在 main.js裏面引入store,而後再全局注入一下,這樣一來就能夠在任何一個組件裏面使用this.$store了:

import store from './store'//引入store new Vue({ el: '#app', router, store,//使用store template: '<App/>', components: { App } })

說了上面的前奏以後,接下來就是歸入正題了,就是開篇說的state的玩法。回到store文件的index.js裏面,咱們先聲明一個state變量,並賦值一個空對象給它,裏面隨便定義兩個初始屬性值;而後再在實例化的Vuex.Store裏面傳入一個空對象,並把剛聲明的變量state仍裏面:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={//要設置的全局訪問的state對象 showFooter: true, changableNum:0 //要設置的初始屬性值 }; const store = new Vuex.Store({ state }); export default store;

實際上作完上面的三個步驟後,你已經能夠用this.$store.state.showFooter或this.$store.state.changebleNum在任何一個組件裏面獲取showfooter和changebleNum定義的值了,但這不是理想的獲取方式;vuex官方API提供了一個getters,和vue計算屬性computed同樣,來實時監聽state值的變化(最新狀態),並把它也仍進Vuex.Store裏面,具體看下面代碼:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ //要設置的全局訪問的state對象 showFooter: true, changableNum:0 //要設置的初始屬性值 }; const getters = { //實時監聽state值的變化(最新狀態) isShow(state) { //方法名隨意,主要是來承載變化的showFooter的值 return state.showFooter }, getChangedNum(){ //方法名隨意,主要是用來承載變化的changableNum的值 return state.changebleNum } }; const store = new Vuex.Store({ state, getters }); export default store;

光有定義的state的初始值,不改變它不是咱們想要的需求,接下來要說的就是mutations了,mutattions也是一個對象,這個對象裏面能夠放改變state的初始值的方法,具體的用法就是給裏面的方法傳入參數state或額外的參數,而後利用vue的雙向數據驅動進行值的改變,一樣的定義好以後也把這個mutations扔進Vuex.Store裏面,以下:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ //要設置的全局訪問的state對象 showFooter: true, changableNum:0 //要設置的初始屬性值 }; const getters = { //實時監聽state值的變化(最新狀態) isShow(state) { //承載變化的showFooter的值 return state.showFooter }, getChangedNum(){ //承載變化的changebleNum的值 return state.changableNum } }; const mutations = { show(state) { //自定義改變state初始值的方法,這裏面的參數除了state以外還能夠再傳額外的參數(變量或對象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,這裏面的參數除了state以外還傳了須要增長的值sum state.changableNum+=sum; } }; const store = new Vuex.Store({ state, getters, mutations }); export default store;

這時候你徹底能夠用 this.$store.commit('show') 或 this.$store.commit('hide') 以及 this.$store.commit('newNum',6) 在別的組件裏面進行改變showfooter和changebleNum的值了,但這不是理想的改變值的方式;由於在 Vuex 中,mutations裏面的方法 都是同步事務,意思就是說:好比這裏的一個this.$store.commit('newNum',sum)方法,兩個組件裏用執行獲得的值,每次都是同樣的,這樣確定不是理想的需求

好在vuex官方API還提供了一個actions,這個actions也是個對象變量,最大的做用就是裏面的Action方法 能夠包含任意異步操做,這裏面的方法是用來異步觸發mutations裏面的方法,actions裏面自定義的函數接收一個context參數和要變化的形參,context與store實例具備相同的方法和屬性,因此它能夠執行context.commit(' '),而後也不要忘了把它也扔進Vuex.Store裏面:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ //要設置的全局訪問的state對象 showFooter: true, changableNum:0 //要設置的初始屬性值 }; const getters = { //實時監聽state值的變化(最新狀態) isShow(state) { //承載變化的showFooter的值 return state.showFooter }, getChangedNum(){ //承載變化的changebleNum的值 return state.changableNum } }; const mutations = { show(state) { //自定義改變state初始值的方法,這裏面的參數除了state以外還能夠再傳額外的參數(變量或對象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,這裏面的參數除了state以外還傳了須要增長的值sum state.changableNum+=sum; } }; const actions = { hideFooter(context) { //自定義觸發mutations裏函數的方法,context與store 實例具備相同方法和屬性 context.commit('hide'); }, showFooter(context) { //同上註釋 context.commit('show'); }, getNewNum(context,num){ //同上註釋,num爲要變化的形參 context.commit('newNum',num) } }; const store = new Vuex.Store({ state, getters, mutations, actions }); export default store;

而在外部組件裏進行全局執行actions裏面方法的時候,你只須要用執行

this.$store.dispatch('hideFooter')

或this.$store.dispatch('showFooter')

以及this.$store.dispatch('getNewNum',6) //6要變化的實參

這樣就能夠全局改變改變showfooter或changebleNum的值了,以下面的組件中,需求是跳轉組件頁面後,根據當前所在的路由頁面進行隱藏或顯示頁面底部的tabs選項卡

<template> <div id="app"> <router-view/> <FooterBar v-if="isShow" /> </div> </template> <script> import FooterBar from '@/components/common/FooterBar' import config from './config/index' export default { name: 'App', components:{ FooterBar:FooterBar }, data(){ return { } }, computed:{ isShow(){ return this.$store.getters.isShow; } }, watch:{ $route(to,from){ //跳轉組件頁面後,監聽路由參數中對應的當前頁面以及上一個頁面 console.log(to) if(to.name=='book'||to.name=='my'){ // to.name來獲取當前所顯示的頁面,從而控制該顯示或隱藏footerBar組件 this.$store.dispatch('showFooter') // 利用派發全局state.showFooter的值來控制 }else{ this.$store.dispatch('hideFooter') } } } } </script> }else{ this.$store.dispatch('hideFooter') } } } } </script>

至此就能夠作到一呼百應的全局響應狀態改變了!

modules 模塊化以及組件中引入 mapGetters、mapActions 和 mapStates的使用

由於在大多數的項目中,咱們對於全局狀態的管理並不只僅一種狀況的需求,有時有多方面的需求,好比寫一個商城項目,你所用到的全局state多是關於購物車這一起的也有多是關於商品價格這一起的;像這樣的狀況咱們就要考慮使用vuex中的 modules 模塊化了,具體怎麼使用modules呢?我們繼續一步一步的走:

首先,在store文件夾下面新建一個modules文件夾,而後在modules文件裏面創建須要管理狀態的js文件,既然要把不一樣部分的狀態分開管理,那就要把它們給分紅獨立的狀態文件了,以下圖:

而對應的store文件夾下面的index.js 裏面的內容就直接改寫成:

import Vue from 'vue'; import Vuex from 'vuex'; import footerStatus from './modules/footerStatus' import collection from './modules/collection' Vue.use(Vuex); export default new Vuex.Store({ modules:{ footerStatus, collection } });

相應的js,其中的 namespaced:true 表示當你須要在別的文件裏面使用( mapGetters、mapActions 接下來會說 )時,裏面的方法須要註明來自哪個模塊的方法:

//collection.js const state={ collects:[], //初始化一個colects數組 }; const getters={ renderCollects(state){ //承載變化的collects return state.collects; } }; const mutations={ pushCollects(state,items){ //如何變化collects,插入items state.collects.push(items) } }; const actions={ invokePushItems(context,item){ //觸發mutations裏面的pushCollects ,傳入數據形參item 對應到items context.commit('pushCollects',item); } }; export default { namespaced:true,//用於在全局引用此文件裏的方法時標識這一個的文件名 state, getters, mutations, actions }
//footerStatus.js const state={ //要設置的全局訪問的state對象 showFooter: true, changableNum:0 //要設置的初始屬性值 }; const getters = { //實時監聽state值的變化(最新狀態) isShow(state) { //承載變化的showFooter的值 return state.showFooter }, getChangedNum(){ //承載變化的changebleNum的值 return state.changableNum } }; const mutations = { show(state) { //自定義改變state初始值的方法,這裏面的參數除了state以外還能夠再傳額外的參數(變量或對象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,這裏面的參數除了state以外還傳了須要增長的值sum state.changableNum+=sum; } }; const actions = { hideFooter(context) { //自定義觸發mutations裏函數的方法,context與store 實例具備相同方法和屬性 context.commit('hide'); }, showFooter(context) { //同上註釋 context.commit('show'); }, getNewNum(context,num){ //同上註釋,num爲要變化的形參 context.commit('newNum',num) } }; export default { namespaced: true, //用於在全局引用此文裏的方法時標識這一個的文件名 state, getters, mutations, actions }

這樣一改就有了關於兩個模塊的state管理文件了 footerStatus.js和collection.js,如今你要運行當前的代碼話,項目會報錯!由於咱們把上面的代碼模塊化分開了,引用的地方尚未改。

接下來我們一塊兒來看看 mapState,mapGetters,mapActions的使用,首先在須要用的組件裏面先導入 import {mapState,mapGetters,mapActions} from 'vuex',導入mapState能夠調用vuex中state的數據,導入mapMutations能夠調用vuex中mutations的方法 ......四個輔助函數 各自對應本身在vuex上的本身。

我們先修正一下隱藏或顯示頁面底部的tabs選項卡(就是上面舉的臨時例子)的組件代碼

<template> <div id="app"> <router-view/> <FooterBar v-if="isShow" /> </div> </template> <script> import {mapState,mapGetters,mapActions} from 'vuex'; //先要引入 import FooterBar from '@/components/common/FooterBar' import config from './config/index' export default { name: 'App', components:{ FooterBar:FooterBar }, data(){ return { } }, computed:{ ...mapState({ //這裏的...是超引用,ES6的語法,意思是state裏有多少屬性值我能夠在這裏放多少屬性值 isShow:state=>state.footerStatus.showFooter //注意這些與上面的區別就是state.footerStatus, //裏面定義的showFooter是指footerStatus.js裏state的showFooter }), //你也能夠用下面的mapGetters來獲取isShow的值,貌似下面的更簡潔 /*...mapGetters('footerStatus',{ //footerStatus指的是modules文件夾下的footerStatus.js模塊 isShow:'isShow' //第一個isShow是我自定義的只要對應template裏v-if="isShow"就行, //第二個isShow是對應的footerStatus.js裏的getters裏的isShow })*/ }, watch:{ $route(to,from){ if(to.name=='book'||to.name=='my'){ this.$store.dispatch('footerStatus/showFooter') //這裏改成'footerStatus/showFooter', //意思是指footerStatus.js裏actions裏的showFooter方法 }else{ this.$store.dispatch('footerStatus/hideFooter') //同上註釋 } } } } </script>

如今項目代碼應該就不會報錯了,好,最後我們再來看一下mapActions的用法,實際上上面的this.$store.dispatch('footerStatus/showFooter')已經算是一種執行相應模塊的action裏的方法了,但有時會牽扯的事件的觸發及傳值,那就會有下面的mapActions用法了,還記得上面的另外一個模塊collection.js嗎?來看一下里面的actions中的方法結構:

const state={ collects:[], //初始化一個colects數組 }; const getters={ renderCollects(state){ //承載變化的collects return state.collects; } }; const mutations={ pushCollects(state,items){ //如何變化collects,插入items state.collects.push(items) } }; const actions={ invokePushItems(context,item){ //觸發mutations裏面的pushCollects ,傳入數據形參item 對應到items context.commit('pushCollects',item); } };

須要傳值來實時變更state.collects裏的數據,那確定要在執行它的地方進行傳值了,因此下面用到它的地方咱們用了個@click來執行這個invokePushItems方法了,而且傳入相應的對象數據item,以下:

<template> <div > <section class="joinState"> <div class="joinStateHead"> <span class="h3">全國改性料通信錄</span> <span class="joinStatus" @click="invokePushItems(item)">加入收藏列</span> </div> </section> </div> </template> <script> import { mapActions } from 'vuex' export default { components:{ conditionFilter }, name: 'bookDetail', data () { return { msg: '', item:{ id:'01', productName: '蘋果', price:'1.6元/斤' } } }, mounted() { this.$store.dispatch('footerStatus/hideFooter') }, methods:{ ...mapActions('collection',[ //collection是指modules文件夾下的collection.js 'invokePushItems' //collection.js文件中的actions裏的方法,在上面的@click中執行並傳入實參 ]) } } </script>

這樣一來,在這個組件裏面操做的 collecttion.js 中的state的數據,在其餘的任何的一個組件裏面都會獲得相應的更新變化了,獲取狀態的頁面代碼以下:

<template> </div> <div> <ul> <li v-for="(val,index) in arrList" :key="index"> <h5>{{val.productName}}</h5> <p>{{val.price}}</p> </li> </ul> </div> </template> <script> import {mapState,mapGetters,mapActions} from 'vuex'; export default { name: 'book', data() { return { } }, computed:{ // ...mapState({ //用mapState來獲取collection.js裏面的state的屬性值 // arrList:state=>state.collection.collects // }), ...mapGetters('collection',{ //用mapGetters來獲取collection.js裏面的getters arrList:'renderCollects' }) } } </script>

至此,vuex中的經常使用的一些知識點使用算是簡單的分享完了。

相關文章
相關標籤/搜索