Vuex小入门

作者: 云中声 | 来源:发表于2020-02-08 10:38 被阅读0次

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

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小入门

    要用一个框架,要先看这个框架是用来解决什么问题的。 Vuex目前为止我觉得作用主要有两个: 解决数据流的问题:子组...

  • 后台管理(4)--- vuex的实际使用(vue)

    今天我们来讨论一下在项目中到底应该怎么使用vuex(vuex还没有入门的同学可以先看这个链接vuex 入门及持久化...

  • 轻松上手Vue - 简化Vuex

    PS: Vuex 对于很多初入门Vue的来说,入门困难,感觉非常绕。 Vuex 是一个专为 Vue.js 应用程...

  • vuex入门详解

    vuex最简单、最详细的入门文档 vuex最简单、最详细的入门文档 如果你在使用 vue.js , 那么我想你可能...

  • vuex入门

    vuex最简单、最详细的入门文档

  • 2020-03-25 vuex 全集

    Vuex入门(1)—— Vuex的设计初衷和简单使用 https://blog.csdn.net/dkr38020...

  • vuex入门

    1.入门使用 (1)引入vuex (2)新建src/vuex文件夹,在vuex中新建store.js文件。文件中引...

  • vuex入门

    Vuex是什么 Vuex是一个专为Vue.js应用程序开发的 状态管理模式 。它采用集中式存储管理应用的所有组件的...

  • Vuex 入门

    Vuex 是什么? 官方给出的解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存...

  • vuex入门

    npm install vuex--save 安装(install 后package.json里的dependen...

网友评论

    本文标题:Vuex小入门

    本文链接:https://www.haomeiwen.com/subject/cpobxhtx.html