利用demo的源码及注释,详细解释Vuex的使用

本文详细介绍了Vue应用中如何使用Vuex进行状态管理和响应式渲染,涉及mutation提交、action触发、计算属性与事件绑定。通过实例演示了状态变更、计算属性获取和事件驱动的组件交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<body>
    <div class="app">
        {{one}}
        <div>{{count}}</div>

        <!-- 15、状态变更 -->
        <div>{{muTwoState}}</div>

        <!-- 24、响应式渲染 -->
        <div>{{ stateTempt }}</div>

        <!-- 9、事件触发,提交mutations -->
        <button @click="changeState()">变更</button>

        <!-- 12、事件触发 -->
        <button @click="changeTwo()">载荷</button>

        <!-- 19、事件触发,通过action更改状态值 -->
        <button @click="temptState()">Action</button>
    </div>
    <script>
        //状态
        const store = new Vuex.Store(
            {
                state: {
                    oneState: 11,
                    arr: [1, 2, 3],
                    twoState: 22,
                    tempt: 33
                },

                //5、store 中的 state 中派生出一些状态;Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。
                //就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
                getters: {
                    arrLength: state => {
                        return state.arr.length
                    }
                },

                //8、更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:
                //每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,
                //并且它会接受 state 作为第一个参数:
                mutations: {
                    changeOneState(state) {
                        //变更状态
                        state.oneState++
                    },

                    // 11、mutation可以提交载荷,也就是接收参数
                    changeTwoState(state, n) {
                        state.twoState += n
                    },

                    //16、大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的mutation会更易读
                    // increment(state, payload) {
                    //     state.count += payload.amount
                    // }
                    //
                    // store.commit('increment',{amount:10})  通知mutation

                    muState(state) {   // 22、真正执行更改state状态值的地方
                        state.tempt++
                    }

                },
                // 18、action类似于mutation,然而action提交的是mutation,而不是直接变更状态;action可以包含任意异步操作
                //action函数接受一个与store实例具有相同方法和属性的context对象,
                //因此你可以调用context.commit提交一个mutation,或者通过context.state和context.getters来获取state和getters。
                actions: {
                    acState(context) {
                        context.commit('muState')   //21、通知mutation 更改state状态值
                    },

                    //25、由于mutation必须同步执行,直接分发mutation是不可以的,而action不会受限制,我们可以在action内部执行任意异步操作 
                    // incrementAsync({ commit }) {
                    //     setTimeout(() => {
                    //         commit('increment')
                    //     }, 1000)
                    // }
                    //action支持同样的载荷方式和对象进行分发(组件事件中)
                    // store.dispatch('incrementAsync', {
                    //     amount: 10
                    // })
                    // store.dispatch({
                    //     type: 'incrementAsync',
                    //     amount" 10
                    // })
                }
            }
        );
        var app = new Vue({
            el: '.app',
            data: {
                one: 1
            },
            methods: {
                changeState() {
                    this.$store.commit('changeOneState')  //  10、提交mutation,或者说通知mutation,进而改变state状态值
                },
                changeTwo() {
                    this.$store.commit('changeTwoState', 10)  //13、通知mutation改变state状态值,并赋予载荷,也就是参数
                },

                // 17、使用mapMutations辅助函数将组件中的methods映射为store.commit调用(高级写法)
                //先在项目组件引入  import { mapMutations } from "vuex"
                //再组件事件中
                //...mapMutations(
                //     [
                //         'increment',   将this.increment()映射为this.$store.commit('increment')  组件方法名与mutation事件名一致
                //         'incrementBy' 将this.incrementBy(amount)映射为this.$store.commit('incrementBy',amount)
                //     ]
                // )
                // ...mapMutations({
                //     add: 'increment'  //将this.add()映射为this.$store.commit('increment')  组件方法名与mutation事件名不同时
                // })

                temptState() {
                    this.$store.dispatch('acState')  //20、通知action,我需要更改state状态值
                }

                //25、mapActions辅助函数组件的methods映射为store.dispatch调用(需要先在根节点注入store)(高级写法)
                // ...mapActions([
                //     'increment',   //将 this.increment() 映射为 this.$store.dispatch('increment')
                //     //mapActions 也支持载荷
                //     'incrementBy'  //将 this.incrementBy(amount) 映射为 this.$store.dispatch('incrementBy',amount)
                // ]),
                // ...mapActions({
                //     add: 'increment'  //将this.add() 映射为 'this.$store.dispatch('increment')'
                // })
            },
            computed: {
                count() {
                    return this.$store.state.oneState  //2、计算属性获取状态值,得到的值是响应的
                },

                //3、 如果在组件中使用的状态值过多的话,大量的计算属性太过冗余,使用辅助函数mapState的话,可以使代码更加简洁
                //在组件中引入 import { mapState } from 'vuex'
                // computed: mapState({
                //     count: state => state.oneState
                // })

                //4、 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。(高级写法)
                // computed: mapState([
                // 映射 this.oneState 为 store.state.oneState  可以在组件中使用this.oneState来调用this.$store.state.oneState
                // 'oneState'
                // ])
                //再高级一点的代码就是
                // ...mapState({

                // })

                //7、mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性(高级写法)
                //在组件中引入
                //import { mapGetters } from 'vuex'
                // ...mapGetters({
                //     // 把 `this.tempt` 映射为 `this.$store.getters.arrLength`
                //     tempt: 'arrLength'
                // })
                //或者
                // ...mapGetters([
                //     'arrLength'
                // ])
                // 把 `this.arrLength` 映射为 `this.$store.getters.arrLength`

                muTwoState() {     //14、计算属性获取state状态值
                    return this.$store.state.twoState
                },

                stateTempt() {  //23、计算属性获取state状态值
                    return this.$store.state.tempt
                }
            },
            mounted() {
                console.log(this.$store.state.oneState);  // 1、状态的简单使用
                console.log(this.$store.getters.arrLength);  //6、状态的派生属性的使用
            },
            store  //注入根组件(ES6写法)
        })
    </script>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值