vue--vuex詳解


  Vuex

    什么是Vuex?

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

      個人理解:Vuex是用來管理組件之間通信的一個插件

    為什么要用Vuex?

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

    Vuex有什么特性?

    怎么使用Vuex?

      引入Vuex.js文件 

      創建實例:

<!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>

    在chrome中顯示:

 

     

     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的數據並顯示在組件中,有幾個步驟:1. 在mutations選項里,注冊函數 函數里面裝邏輯代碼。2.在組件里,this.$store.commit('change',payload)  注意:提交的函數名要一一對應  3.觸發函數,state就會相應更改 4.在組件的計算屬性里 this.$store.state 獲取你想要得到的數據

 

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

        actions和mutations的區別

          1.Actions 提交的是 mutations,而不是直接變更狀態。也就是說,actions會通過mutations,讓mutations幫他提交數據的變更。

          2.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.statecontext.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)
                 
             }
         }

     2. 在組件里: changeNumAnsyc:function(){this.$store.dispatch('add', 5);}  將dispatch“指向”actions選項里的函數

     3. 在mutations選項里,要有對應的函數 changeAsync:function(state,a){console.log(state.num +=a);}

    總結

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

    對Vuex的了解就先到這了,細節以后在補充。。。。。待續

    

 

  

         


免責聲明!

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



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