vuex基础+示例

为什么用vuex?
组件子间传值有局限,不能处理复杂的情况,
什么情况下使用:
两个组件或更多组件都要用到同样的数据,跨多个组件传值,记录用户登录信息,(不需要多个组件传递用户信息,需要的时候去vuex里面去取就可以了)
新建vuex:
state:相当于data,数据不能随便更改,只能通过mutations(相当于methods)修改
getters:相当于computed,计算属性,依赖改变触发
mutations:相当于methods,每个方法都有两个参数,第一个是state,不需要传,第二个是data
actions:相当于 async methods 存放异步的方法
modules:模块

 const store = new Vuex.Store({
            state: { 
            },
            getters: { 
            },
            mutations: {
            },
            actions: {
            },
            modules: {
            }
        })

示例:点击组件内的按钮修改vuex里面的值,同时另一个组件使用watch监听 s t o r e . s t a t e . m s g 同 步 修 改 , 或 者 另 一 个 组 件 直 接 在 模 板 内 显 示 store.state.msg同步修改,或者另一个组件直接在模板内显示 store.state.msgstore.state.msg

    <div id="app">
        <aaa></aaa>
        <hr>
        <bbb></bbb>
    </div>
    <script>
        const store = new Vuex.Store({
            state: { //相当于data
                msg: 20,
            },
            //相当于methods 方法  state里面的值不允许直接修改,需要在mutations里面修改
            mutations: {
                setAdd(state, data) {
                    state.msg = data
                }
            },
        })
        Vue.component('aaa', {
            template: `<div>
                         <h1>{{zj}}</h1>
                        <button @click="add">增加</button>
                      </div>`,
            methods: {
                add() {
                    this.zj += 2
                    this.$store.commit('setAdd', this.zj)
                }
            },
            data() {
                return {
                    zj: this.$store.state.msg
                }
            },
        })
        Vue.component('bbb', {
            template: `<h1>{{zj}}</h1>`,
            data() {
                return {
                    zj: this.$store.state.msg
                }
            },
            watch: {
                '$store.state.msg'(newValye, oldValue) {
                    this.zj = this.$store.state.msg
                    console.log(111);
                }
            },
        })
        new Vue({
            el: '#app',
            store,
        })
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值