vuex的使用

vuex是配合vue一起使用的一個狀態管理工具。
我一般使用它來保存一些全局的數據,例如用戶登陸信息,用戶身份信息,總之一些在不少頁面都會使用到的信息,都保存在vuex裏面,用的時候就不須要再去請求接口了,直接去vuex裏面拿就能夠了。
先放官網地址html

安裝

npm install vuex --save

配置

我實在vue-cli環境中使用vuex的,因此這裏就以這個環境做爲項目文件結構來寫配置了。
先在src/assets文件夾中新建一個vuex/store.js文件,建好以後在文件中寫以下代碼:vue

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        name: 'xiaoming',
        count: 1
    }
})
export default store

在main.js中引入store.js:webpack

import store from '@/assets/vuex/store';

在全局構造器中註冊一下:(這裏千萬別忘了)

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  store: store   //在根實例下面註冊store,至關於全局註冊,能夠全局調用
})

//題外話
//在vue-cli中,引入某些特定後綴的文件是不須要寫全後綴的,就像上面這個store
//由於在config/webpack.base.conf.js文件中,有這樣一段代碼:
    resolve: {
        extensions: ['.js', '.vue', '.json'],  //這些後綴的文件能夠不寫,能夠本身隨意添加
        alias: {   //模塊別名定義,方便後續直接引用別名,無須多寫長長的地址
          'vue$': 'vue/dist/vue.esm.js',
          '@': resolve('src'),  //從src文件夾開始尋找文件
        }
    }

到這裏,vuex已經在你的項目中安裝好而且可使用了。你只須要在vue的html的部分寫上以下代碼:es6

<div>{{$store.state.name}}</div>       //頁面中會顯示'xiaoming'

或者在構造器裏面寫:web

console.log(this.$store.state.name);      //打印'xiaoming'

html代碼書寫取值的時候能夠不加this,script代碼中必須加this。vuex

使用

1.state狀態對象的訪問(我把state理解成vue構造器中的data)vue-cli

state裏面存放一些數據,例如用戶姓名、性別、身份證號等等。以前個人訪問方式是:npm

{{$store.state.name}}

可是上面這種寫法太長了,並且看起來不直觀,查閱過文檔以後我發現,訪問state對象能夠有如下三種寫法:json

//若是我想在頁面中只寫{{name}},能夠這樣寫:

 1. computed: {
        name() {
            return this.$store.state.name;
        }
    }
    
 2. import {mapState} from 'vuex';
    computed: mapState({
        name: state => state.name    //es6箭頭函數
    })
 
 3. import {mapState} from 'vuex';
    computed: mapState(['name']);    //這種寫法最簡單,推薦

2.訪問mutations方法(我把mutations理解成vue構造器中的methods)app

先在store.js中寫上以下代碼:

const store = new Vuex.Store({
    state: {
        name: 'xiaoming',
        count: 1
    },
    mutations: {
        add(state,num) {   //接收一個外部參數
            state.count += num;
        },
        reduce(state) {
            state.count --;
        }
    }
})

原先我調用add和reduce方法的時候,寫法是:

<div>{{count}}</div>
<button @click="$store.commit('add',10)">點擊加十</button>
<button @click="$store.commit('reduce')">點擊減一</button>

可是這種調用方法的寫法也太長,須要寫上$store.commit這種東西,太囉嗦。
模仿訪問state的方法,它也有另一種便捷的寫法:

import {mapState,mapMutations} from 'vuex';
methods: mapMutations(['add','reduce']),
//須要注意的是,state寫在computed裏面,而mutations寫在methods裏面,由於它是在@click以後的方法

如今你能夠這樣調用它:

<div>{{count}}</div>
<button @click="$store.commit('add',10)">點擊加十</button>
<button @click="reduce">點擊減一</button>

3.訪問getters(我把getters理解成vue構造器中的computed)

getters就像一道門,每操做一次數據,都會通過一次它。

如今,在store.js中加入getters代碼:

const store = new Vuex.Store({
    state: {
        name: 'xiaoming',
        count: 1
    },
    mutations: {
        add(state,num) {   //接收一個外部參數
            state.count += num;
        },
        reduce(state) {
            state.count --;
        }
    },
    getters: {
        add100(state) {
            return state.conut += 100;   //每操做一次count,它都會加上100
        },
        changename(state) {
            return state.name + 'c';     //每操做一次name,它都會拼接上一個c    
        }
    }
})

怎麼調用它呢?模仿state的調用方法。
由於它們都是對數據進行操做,不涉及方法,因此getters也寫在computed中。

import {mapState,mapMutations,mapGetters} from 'vuex';

//如今來看computed的代碼要怎麼寫
//在寫state的時候,咱們把computed中的代碼寫成了這樣:
//computed: mapState(['name']);
//那若是如今再加入mapGetters,就須要改變computed的樣子,具體應該這樣寫:

computed: {
    ...mapState(['name','count']),   //es6擴展運算符,用map必須得用這個,不然會報錯
    ...mapGetters(['add100','changename']),
    count2: function() {
        return this.$store.state.count;
    }
}

此時,每當你操做一次button按鈕,不管是加法仍是減法,它都會對count進行+100的操做。固然,此時的name是不會改變的,即便你引入了changename方法,但由於沒有改變過name,因此就不會出發changename方法。

4.訪問actions

actions與getters的用法類似,可是它是異步調用,寫在methods裏面。(說實話我是沒看懂這個actions有啥用)

先來完善一下咱們的store.js中的代碼:

const store = new Vuex.Store({
    state: {
        name: 'xiaoming',
        count: 1
    },
    mutations: {
        add(state,num) {   //接收一個外部參數
            state.count += num;
        },
        reduce(state) {
            state.count --;
        }
    },
    getters: {
        add100(state) {
            return state.conut += 100;   //每操做一次count,它都會加上100
        },
        changename(state) {
            return state.name + 'c';     //每操做一次name,它都會拼接上一個c    
        }
    },
    actions: {
        add1(context) {                    //參數context即全局上下文對象,store
            context.commit('add',10);      //經過context調用add方法
            setTimeout(()=>{context.commit('reduce')},3000)
        },
        reduce1({commit}) {                //{commit}是另外一種傳參方式,一個封裝好的commit
            commit('reduce');
        }
    }
})

寫好actions方法了以後,就來調用它,調用方法跟mutations差很少:

methods: {
    ...mapMutations(['add','reduce']),
    ...mapActions(['add1','reduce1']),
    aa(i) {
        console.log(i)
    }
}

在html代碼中使用:

<button @click="add1">作加法</button>
<button @click="reduce1">作減法</button>

reduce1方法調用了mutations中的reduce方法,每次點擊減1;
add1調用了mutations中的add方法,每次點擊加10,同時在3秒鐘以後,會調用一次減法,減去1;
由於還有getters的設置,因此每次操做的時候還會再加100。

以上就是vuex的大體用法了,我平時只有state用的比較多。我對vuex的理解很淺,若有不對的地方,請指正。

相關文章
相關標籤/搜索