Vuex的使用

什么是Vuex

Vuex是Vue配套的公共数据管理工具,我们可以将共享的数据保存到vuex中,方便整个程序中的任何组件都可以获取和修改vuex中保存的公共数据。

下载地址,vuex.js在dist目录中
注意:导入Vuex之前必须先导入Vue

Vuex的使用

1.创建Vuex对象

 // 创建vuex对象
const store = new Vuex.Store({
    //这里的state就相当于组件中的data,就是专门用于保存共享数据的
    state: {
        msg:"hello world"
    }
})

2.在祖先组件中添加store的key保存Vuex对象

Vue.component("grandfather", {
    template: '#grandfather',
    //只要在祖先组件中保存了Vuex对象,那么祖先组件和所有的后代组件以使用Vuex中保存的共享数据
    store: store,
    //爸爸组件
    components: {
        "father": {
            template: "#father",
            //儿子组件
            components: {
                "son": {
                    template: "#son"
                }
            }
        }
    }
});

3.使用Vuex中保存的数据

<div id="app">
    <grandfather></grandfather>
</div>
<template id="grandfather">
    <div>
    // 使用格式必须如下,msg前面部分固定
        <p>{{this.$store.state.msg}}</p>
        <father></father>
    </div>
</template>

修改共享数据的方法(mutations属性)

不推荐直接修改共享数据:如果多个组件都修改了共享的数据,那么后期数据发生了错误,我们如果需要取调试错误,就需要把每一个修改了共享数据的组件都检查一遍,非常低效。

mutations中定义方法

const store = new Vuex.Store({
    //用于保存共享数据
    state: {
        count:0 
    },
    //用于保存修改共享数据的方法
    mutations:{
        mAdd(state){
            state.count = statcount+1;
        },
        mSub(state){
            state.count = statcount-1;
        }
    }
})

注意:在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数,state中就保存了共享的数据

方法的调用

Vue.component("grandfather", {
    template: '#grandfather',
    store: store,
    components: {
        "father": {
            template: "#father",
            methods:{
                add(){
                    //不建议使用 this.$store.state.count=this.$store.state.count+1;
                    this.$store.commit('mAdd');
                }
            }
        }
    }
});

getters属性

专门用于定义计算属性的,作用类似于computed计算属性

计算属性是基于它们的依赖进行缓存的:计算结果缓存起来,只要计算值不变,再次调用不会再次执行函数,会直接返回计算结果

const store = new Vuex.Store({
    //用于保存共享数据
    state: {
        msg:"hello world" 
    },
    //用于保存修改共享数据的方法
    mutations:{
    },
    getters:{
        formart(state){
            return state.msg+"你好";
        }
    }
});

调用方法:

{{this.$store.getters.formart}}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值