vue--vuex详解

  Vuex

    什么是Vuex?html

       官方说法:Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的全部组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。vue

      我的理解:Vuex是用来管理组件之间通讯的一个插件git

    为何要用Vuex?ajax

      咱们知道组件之间是独立的,组件之间想要实现通讯,我目前知道的就只有props选项,但这也仅限于父组件和子组件之间的通讯。若是兄弟组件之间想要实现通讯呢?嗯..,方法应该有。抛开怎么实现的问题,试想一下,当作中大型项目时,面对一大堆组件之间的通讯,还有一大堆的逻辑代码,会不会很抓狂??那为什么不把组件之间共享的数据给“拎”出来,在必定的规则下管理这些数据呢? 这就是Vuex的基本思想了。vuex

    Vuex有什么特性?chrome

    怎么使用Vuex?app

      引入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的了解就先到这了,细节之后在补充。。。。。待续

相关文章
相关标签/搜索