Vuex的安裝、使用及注意事項


使用Vuex的步驟:

(1)安裝:

  1.使用npm安裝:

    

1
npm install vuex  --save

  

  2.使用script標簽引入

    

1
2
3
< script  src="/path/to/vue.js"></ script >
 
< script  src="/path/to/vuex.js"></ script >

  

  如果使用第一種方式安裝Vuex插件,在使用Vuex插件之前需要在main.js入口文件中

    1‘ 使用import方式引入Vuex

      

1
import  Vuex from ‘vuex’

  

    2‘ 使用Vue的插件引入函數Vue.use()使用Vuex

      

1
Vue.use(Vuex);

  

(2)安裝之后可以通過Vuex實例對象的Store方法創建一個store對象:

  

復制代碼
var store = new Vuex.Store({
    state:{
        NewMsg:{
            Msgs:[
                {
                    title:'暫無消息',
                    content:'暫無消息!',
                    url:'#no_msg',
                    id:'no_msg'
                }
            ]
        },
    },
    mutations:{
        modifyMsg (state,Obj){
            if(state.NewMsg.Msgs[0].id === 'no_msg'){
                state.NewMsg.Msgs.shift();
            }
            var obj = {
                title:Obj.title,
                content:Obj.content
            };
            obj.id = 'Msg_' + Obj.id;
            obj.url = '#' + obj.id;
            state.NewMsg.Msgs.push(obj);
        }
    },
    actions:{
        fetchMsg (context){
            $.ajax({
                    url:'PHP/GetMsgs.php',
                    type:'GET',
                    data:{},
                    dataType:'json',

                    success:function(response){
                        if ( typeof response === 'string') {
                            response = JSON.parse(response);
                        }
                        console.log(response);
                        $(response).each(function(k,v){
                            // console.log(v.id+v.title+v.content);
                            context.commit('modifyMsg',v);
                        });
                    }
                });
        }
    }
});
復制代碼

 

(3)在Vue實例中注冊store對象:

  

復制代碼
new Vue({
  el: '#app',
  router,
  store,
  created (){
      store.dispatch('fetchMsg');
  },
  template: '<App/>',
  components: { App }
})
復制代碼

 

(4)在組件中使用state數據:

  必須通過computed屬性使用state數據!否則state屬性中的數據發生更改時不會反映在組件上!

  

復制代碼
export default {
        computed: {
            Msgs (){
                var Msgs = this.$store.state.NewMsg.Msgs;
                return Msgs;
            }
        }
    }
復制代碼

 

注意事項: 

  基本組成:

    注意vuex中幾個核心概念:

    state、mutations、actions、 getters、module

    state:用於存儲數據,類似vue實例的data屬性。

    mutations:用於遞交更改,對state對象中的屬性數據進行更改。

    actions:用於進行遞交異步更改,通過調用mutations實現對數據的更改。

    getters:可以認為是store的計算屬性;與計算屬性一樣,getter的返回值會根據它的依賴緩存起來,且只有當它的依賴值發生變化才會被重新計算

    mapGetters:輔助函數,將 store 中的 getter 映射到局部計算屬性:

    module:將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割

    

 

  actions與mutations的區別:

    其中actions區別於mutations的地方在於mutations只能進行同步更改,而actions中的更改可以是異步執行。所以基本上所有用戶執行的直接數據更改都是觸發mutations屬性

    函數執行,而需要與后端進行數據交互的數據更改通常是通過actions屬性函數去執行。

 

  定義actions與mutations屬性函數的注意事項:

    其中定義mutations屬性函數時必須傳遞的第一個參數是state,因為要對state進行更改,第二個參數代表傳入的新參數。mutations屬性函數只接受兩個參數,如果要同時更

    改多個屬性值,可以通過對象傳入。

     在actions屬性函數中可以通過context.commit()方法觸發mutations屬性函數。定義actions屬性函數時,必須傳遞的第一個參數是context,用於觸發mutations函數。

 

  觸發actions與mutations屬性函數的方法:

    在子組件中通過this.$store.commit()方法觸發mutations屬性函數。在注冊store的Vue實例中(第三步中將會講到)可以通過store.commit()觸發。

    commit函數第一個參數是mutations的屬性函數名,第二個參數是傳入的新值。

    actions屬性函數中可以進行異步操作,比如通過ajax或者Vue.Resource()進行數據獲取,獲取數據后再通過context.commit()觸發更改。

     觸發actions屬性函數使用this.$store.dispatch()或者store.dispatch() (在注冊store的Vue實例中)函數。dispatch函數傳遞的一個參數是actions屬性函數名稱。如果希望在

    Vue實例創建完成還未掛載時就從后端獲取數據,則可以在created鈎子函數中調用actions屬性函數。

 

  在組件中訪問數據中心state的注意事項:

    在Vue實例中可以通過this.$store.state對象獲取state中的數據。如果希望在state中的數據發生更改之后,組件會自動更新,則應該使用組件的computed屬性定義數據,而

    不是通過data屬性定義。如果使用data定義組件數據,則state中的數據發生更改之后組件不會發生變化。

export default {
        computed: {
            Msgs (){
                var Msgs = this.$store.state.NewMsg.Msgs;
                return Msgs;
            }
        }
    }

  mapGetters使用:輔助函數僅僅是將 store 中的 getter 映射到局部計算屬性

import { mapGetters } from 'vuex' export default { // ... computed: { // 使用對象展開運算符將 getter 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }

  module使用注意事項:  

由於使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象;當應用變得非常復雜時,store 對象就有可能變得相當臃腫。

為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割:

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 的狀態 store.state.b // -> moduleB 的狀態

 

如果你希望使用全局 state 和 getterrootState 和 rootGetter 會作為第三和第四參數傳入 getter,也會通過 context 對象的屬性傳入 action


免責聲明!

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



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