vuex簡(jiǎn)單入門

vue

此文章沒(méi)有官網(wǎng)那么詳細(xì),僅僅給剛要入坑vuex的讀者的一些幫助,大神請(qǐng)繞道,有幫助的請(qǐng)給個(gè)贊~~
vuex是專為vue.js提供的狀態(tài)管理模式。使用是非常簡(jiǎn)單的,記錄一下具體使用步驟。

簡(jiǎn)述作用

它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化。

說(shuō)得通俗點(diǎn)就是,在vue組件中,多個(gè)組件要用到同一個(gè)數(shù)據(jù)源,并且通過(guò)這個(gè)數(shù)據(jù)源渲染視圖,并且數(shù)據(jù)源發(fā)生變化了,組件都要響應(yīng)式變化。而維護(hù)這個(gè)數(shù)據(jù)的方案就是vuex.

安裝

CDN方式
<script src="https://unpkg.com/vuex"></script>

引入vue.js后直接引入,即可自動(dòng)安裝

npm方式
npm install vuex --save
yarm方式
yarn add vuex

如果是在模塊化的打包系統(tǒng)的話,必須顯式安裝vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

官網(wǎng) :狀態(tài)管理模式的應(yīng)用一般包含幾個(gè)部分

state,驅(qū)動(dòng)應(yīng)用的數(shù)據(jù)源;

view,以聲明方式將 state 映射到視圖;

actions,響應(yīng)在 view 上的用戶輸入導(dǎo)致的狀態(tài)變化。

state

state就是存儲(chǔ)數(shù)據(jù)源的容器,可以簡(jiǎn)單這里理解,好比在vue組件中的那個(gè)data一樣,只不過(guò)這是在vuex存儲(chǔ)數(shù)據(jù)的容器。

首先用new Vuex.Store()創(chuàng)建vuex實(shí)例

const store = new Vuex.Store({
    state:{
        count : 0
    }
})

如果在模塊化打包系統(tǒng)(vue-cli)中是,新建一個(gè)store.js

import vue from 'vue'
import Vuex from 'vuex'
vue.use(Vuex)
const store = new Vue.Store({
    state:{    // 存儲(chǔ)數(shù)據(jù)的容器
        count : 0
    }
})

export default store

數(shù)據(jù)已經(jīng)有了,怎么在具體組件上面顯示數(shù)據(jù)。一般來(lái)說(shuō),我們是將store掛在根組件上。這樣所有的組件都能拿到store的數(shù)據(jù)。
假設(shè)是在模塊化打包系統(tǒng)中(vue-cli),在main.js

import Vue from 'vue'
import App from './App'
import vuex from 'vuex'
import store from '@/store/store'
Vue.use(vuex)


new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

此時(shí)store已經(jīng)掛在vue的根組件上面了,所以我們?cè)诟M件上面輸出根組件就可以看到store
在App.vue中

<template>
  <div id="app">
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
  },
  created(){
    // 輸出根組件
    console.log(this)
  }
}
</script>
vuex

可以看到根組件的store就是我們之前定義的store,這里我們先只關(guān)注state,而this.store.state.count就是我們?cè)趕tore.js定義在state的count。

我們?cè)诮M件上訪問(wèn)count就是this.$store.count,不過(guò)要注意的是要想實(shí)時(shí)響應(yīng)count的值的話,就要寫在計(jì)算屬性上面

<div id="app">
    {{count}}
</div>
computed:{
    count(){
        return this.$store.state.count
    }
}

getter

有時(shí)候我們需要從 store 中的 state 中派生出一些狀態(tài),比如我不直接讀取state里面值,我想對(duì)這里面的值進(jìn)行一些操作在返回就可以用到getter

import vue from 'vue'
import Vuex from 'vuex'
vue.use(Vuex)
const store = new Vue.Store({
    state:{    // 存儲(chǔ)數(shù)據(jù)的容器
        count : 0,
        list:[
            {id:0,name :'zhangsan',status:true},
            {id:1,name :'lisi'status:false},
            ...
        ]
    },
    getters:{
        getLists(state) {
             return state.list.filter(item => item.status)
        }
    }
})

export default store

上面的例子,我需要對(duì)list進(jìn)行一些操作在輸出值,不是直接拿到list的值,就可以用到getter了
Getter 接受 state 作為其第一個(gè)參數(shù):

怎么在組件中訪問(wèn)getter?

通過(guò)屬性訪問(wèn)

Getter 會(huì)暴露為 store.getters 對(duì)象,你可以以屬性的形式訪問(wèn)這些值:

store.getters.doneTodos //  [{ id: 1, name: 'zhangsan', status: true },...]

在上面例子就是

<div id="app">
    {{count}}
</div>
computed:{
    count(){
        return this.$store.state.count
    },
    getList(){
        return this.$store.getters.getLists
    }
}
通過(guò)方法訪問(wèn)

可以通過(guò)讓 getter 返回一個(gè)函數(shù),來(lái)實(shí)現(xiàn)給 getter 傳參。這種方式對(duì)列表篩選的需求特別有用

getters: {
  getListById: (function (state) {
      return function (id) {
        return state.list.find(function (item) {
          return item.id === id;
        });
      };
  });
}

上面例子中

this.$store.getters.getListById(0) // [{id:0,name :'zhangsan',status:true}]

注意,getter 在通過(guò)方法訪問(wèn)時(shí),每次都會(huì)去進(jìn)行調(diào)用,而不會(huì)緩存結(jié)果。
其他更多getter東西請(qǐng)參考官網(wǎng)文檔,這里不深究~

mutation

既然我們已經(jīng)有了讀了,那接下來(lái)是寫的操作了,官網(wǎng)上說(shuō)

你不能直接改變 store 中的狀態(tài)。改變 store 中的狀態(tài)的唯一途徑就是顯式地提交 (commit) mutation。這樣使得我們可以方便地跟蹤每一個(gè)狀態(tài)的變化,從而讓我們能夠?qū)崿F(xiàn)一些工具幫助我們更好地了解我們的應(yīng)用。

注意這里多了兩個(gè)概念 mutation和commit 先不要混淆

接上面的store.js,我們?cè)趘uex的實(shí)例store里面新增個(gè)mutation對(duì)象,這個(gè)對(duì)象存儲(chǔ)這我們想要對(duì)state對(duì)象里數(shù)據(jù)源的各種操作,而這些具體的操作的函數(shù)就叫 commit

import vue from 'vue'
import Vuex from 'vuex'
vue.use(Vuex)
const store = new Vue.Store({
    state:{    // 存儲(chǔ)數(shù)據(jù)的容器
        count : 0
    },
    mutations:{
        increase(state,n){
            state.count += n
        }
    }
})

export default store

在mutation里面定義的commit函數(shù),函數(shù)就是我們實(shí)際進(jìn)行狀態(tài)更改的地方,并且它會(huì)接受 state 作為第一個(gè)參數(shù)。也可以傳入額外參數(shù)。

例子中的n就是額外參數(shù)。
那我們?cè)诰唧w組件中,怎么出發(fā)這個(gè)mutation里面的修改狀態(tài)的函數(shù)。

我們回到app.vue,比如我們像實(shí)現(xiàn)一個(gè)小需求,在input輸入框中輸入數(shù)字,然后把這個(gè)數(shù)字和count相加。

<template>
  <div id="app">
        <div>{{counter}}</div>
        <input type="text" v-model="number">
        <button @click="increment">相加</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    number:''
  },
  methods:{
    increment(){
      this.$store.commit('increment',parseInt(this.number))
    }  
  }
}
</script>

首先我們要知道,在vuex中不能直接的改變state的狀態(tài),要通過(guò)顯式的提交一個(gè)commit去出發(fā)mutation里面的改變狀態(tài)的函數(shù)。

在組件中,我們用store.commit('increment')去出發(fā)mutation的函數(shù),而上面使用this.$store.commit('定義在mutation的函數(shù)名','額外參數(shù)')觸發(fā)。

當(dāng)然我們傳遞的額外參數(shù)應(yīng)該也可以是個(gè)對(duì)象更加貼近具體需求

mutations:{
    increase(state,payload){
        state.count += payload.n
    }
}

相應(yīng)的觸發(fā)寫法

this.$store.commit('increment', {
  n: 10
})

還可以用另一種直接包含type屬性的對(duì)象提交mutation

this.$store.commit({
  type: 'increment',
  amount: 10
})

當(dāng)然對(duì)于mutation的額外注意事項(xiàng)和東西可以查看官網(wǎng)文檔

action

現(xiàn)在又多了個(gè)action的概念了,Action和mutation類似,按照官網(wǎng)說(shuō)的:不同之處就是

Action 提交的是 mutation,而不是直接變更狀態(tài)。

Action 可以包含任意異步操作。

import vue from 'vue'
import Vuex from 'vuex'
vue.use(Vuex)
const store = new Vue.Store({
    state:{    // 存儲(chǔ)數(shù)據(jù)的容器
        count : 0
    },
    mutations:{
        increase(state,n){
            state.count += n
        }
    },
    actions:{
        increase (context) {
          context.commit('increase')
        }
    }
})

export default store

注意寫在store.js的mutation和action都是帶有s的復(fù)數(shù)形式

Action 函數(shù)接受一個(gè)與 store 實(shí)例具有相同方法和屬性的 context 對(duì)象,因此你可以調(diào)用 context.commit 提交一個(gè) mutation,或者通過(guò) context.state 和 context.getters 來(lái)獲取 state 和 getters。

這里為什么說(shuō)context對(duì)象是與store實(shí)例具有相同方法和屬性的對(duì)象,先不深究,后面會(huì)講到。

觸發(fā)action

Action 通過(guò) store.dispatch 方法觸發(fā)

store.dispatch('increase')

寫在上面代碼就是

this.$store.dispatch('increase')

其實(shí)很多人應(yīng)該會(huì)在想,既然又了mutation了,那action不就多此一舉了嗎,關(guān)鍵還真不是,因?yàn)閙utation是必須同步執(zhí)行的,不能保護(hù)又異步的代碼,而action不受限制,我們可以在action里面執(zhí)行異步操作
參考官網(wǎng)的例子

actions: {
 incrementAsync (context) {
   setTimeout(() => {
     context.commit('increment')
   }, 1000)
 }
}

和mutation一樣,同樣支持荷載形式觸發(fā)對(duì)象方式觸發(fā)

store.dispatch('incrementAsync', {
 amount: 10
})
store.dispatch({
 type: 'incrementAsync',
 amount: 10
})

具體其他注意事項(xiàng),請(qǐng)參考官網(wǎng)文檔

module

module的出現(xiàn)是為了解決,當(dāng)應(yīng)用變得非常復(fù)雜時(shí)候,store對(duì)象會(huì)變得異常臃腫,與是vuex運(yùn)行我們對(duì)store對(duì)象分模塊管理。

每個(gè)模塊都有自己的state、mutation、action、getter和嵌套的module。

參照官網(wǎng)例子

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)

到此就是簡(jiǎn)單的入門知識(shí)了,希望讀者對(duì)vuex能有個(gè)簡(jiǎn)單的概念,再去看官網(wǎng)的文檔就非常容易理解了~

歡迎訪問(wèn)我的個(gè)人網(wǎng)站zhengyepan

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 安裝 npm npm install vuex --save 在一個(gè)模塊化的打包系統(tǒng)中,您必須顯式地通過(guò)Vue.u...
    蕭玄辭閱讀 3,038評(píng)論 0 7
  • vuex是一個(gè)狀態(tài)管理模式,通過(guò)用戶的actions觸發(fā)事件,然后通過(guò)mutations去更改數(shù)據(jù)(你也可以說(shuō)狀態(tài)...
    Ming_Hu閱讀 2,129評(píng)論 3 3
  • ### store 1. Vue 組件中獲得 Vuex 狀態(tài) ```js //方式一 全局引入單例類 // 創(chuàng)建一...
    蕓豆_6a86閱讀 788評(píng)論 0 3
  • 如果你在使用 vue.js , 那么我想你可能會(huì)對(duì) vue 組件之間的通信感到崩潰 。 我在使用基于 vue.js...
    BrightenSun閱讀 5,380評(píng)論 6 21
  • vuex是什么? Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開(kāi)發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組...
    ysp123閱讀 239評(píng)論 0 0

友情鏈接更多精彩內(nèi)容