Vuex小入门

要用一个框架,要先看这个框架是用来解决什么问题的。

Vuex目前为止我觉得作用主要有两个:

  1. 解决数据流的问题:子组件只能通过props接收参数,但不能直接修改参数值,在没有vuex的情况下,只能通过冒泡解决,而vuex解决了这一问题。
  2. 实现了关键数据的集中管理

vuex核心总共有四个部分:

  1. state,这是数据的存储部分,下面是一个简单的例子(为了方便,都是直接引用cdn在html页面上测试,没有使用node)
//html部分
    <div id="example_6_1">
       <div2 ></div2> 
    </div>
    <div id ="example_6_2">
        <button2></button2>
    </div>
//script部分
  Vue.component('div2',{
    template:`<div>{{count}}</div>`,
    computed: {
        count(){
            return this.$store.state.count; 
        }
    },
})
Vue.component('button2',{
    template:`<button v-on:click="click_event">{{count}} add 1</button>`,
    computed:{
        count(){
            return this.$store.state.count;
        }
    },
    methods:{
        click_event:function(){
            console.log("the button is clicked once")
        }
    }
})
var store  = new Vuex.Store({
    state:{
        count:0
    },
    mutations:{
        increment(state){
            state.count++;
        }
    }
})
new Vue({
    el:"#example_6_1",
    store:store
})

new Vue({
    el:"#example_6_2",
    store:store
})

例子实现的是简单的两个组件都以vuex.store对象进行实例化,并将store.state.count属性进行显示,唯一需要注意的地方是,组件在读取自己内部绑定的store对象时,必须写为this.$store.state.XXXX,这是为了区分组件定义成员和用户定义的成员的。

  1. mutations,这里感觉是用了js动态的特性,简单来说就是子组件通过this.$store.commit('function_name')的方式实现对vuex中state的操作
    这里将上述的例子在稍微改动
 Vue.component('button2',{
    template:`<button v-on:click="click_event">{{count}} add 1</button>`,
    computed:{
        count(){
            return this.$store.state.count;
        }
    },
    methods:{
        click_event:function(){
            console.log("the button is clicked once")
            this.$store.commit("increment");
        }
    }
})

这样就实现了按钮按下时两个组件显示数值同时+1的操作

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 10,097评论 7 61
  • 系列文章:Vue 2.0 升(cai)级(keng)之旅Vuex — The core of Vue applic...
    6ed7563919d4阅读 10,006评论 2 58
  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 12,676评论 1 33
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,295评论 0 6
  • 小作者:张皓涵 我喜欢练跆拳道,每个周六上午我都要去上跆拳...
    张皓涵阅读 2,744评论 0 0