vuex 核心理念 及使用方法

vuex

• 参考网址:https://vuex.vuejs.org/zh/guide/mutations.html
• Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
• 每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
• Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
• 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
• Vue适用于中大型单页面应用
• 数据传递:把各个组件共享的状态抽离出来,并且每个组件都可以使用它,并且还可以更改它;既然是公共状态,当其中组件把这个公共状态更改以后,凡是依赖这个公共状态的组件都要更新;
• 在使用vuex的时候要给实例先写上store属性
• 单向数据流
• state,驱动应用的数据源;
• view,以声明方式将 state 映射到视图;
• actions,响应在 view 上的用户输入导致的状态变化。

在这里插入图片描述

核心概念

state
• 如果这个数据是好几个组件共享的,这个数据放到VUEX的state上;如果这个数据只有当前这一个组件使用,那么放到对应的组件的data中
• state在vuex中类似于vue实例中的data,是用来储存数据的
• Vuex 使用单一状态树(状态就是数据)
• state里的数据最好放在实例或组件的计算属性中使用,因为当state里的数据更新后,所有使用它的数据也会立刻更新
• mapState 辅助函数;当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性
• 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
• 对象展开运算符,可以在计算属性中将mapstate函数返回的对象展开
getter
• vue允许定义getter,在store(vuex的实例)中的计算属性,也会被缓存;当依赖的值发生变化,才会改变
mutations
• mutation用来修改state中的值
• vuex更改store中状态的唯一办法就是commit
• mutation 这个对象中的函数的第一个参数的实参都是state;
• 在mutation的方法中,都是同步事务,不支持异步;(追踪工具追踪不到)
actions
• actions 支持异步,这里面提交一个mutation的动作
• actions里的方法的第一个参是store上的commit(第一个参必须加大括号)
module
• 这个modules会把各自模块的state,getters,mutations,actions最终都会注入到该Store中(相当于在store添加了一个键值对)
• 把数据模块化,modules引入的模块,最后都相当于放入了state中
mutations
• mutation用来修改state中的值
• vuex更改store中状态的唯一办法就是commit
• mutation 这个对象中的函数的第一个参数的实参都是state;
• 在mutation的方法中,都是同步事务,不支持异步;(追踪工具追踪不到)

例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <first></first>
        <second></second>
        <div>{{this.$store.state.count}}</div>
    </div>
    
    <script src="../../node_modules/vue/dist/vue.js"></script>
    <script src="../../node_modules/vuex/dist/vuex.js"></script>
    <script>
        let store = new Vuex.Store({
            state:{
                count:100,  // count : 这就是公共的数据
                shop:[{name:"奔驰"},{name:"奥迪"}]
            },
            getters:{ 
                // getters : vue允许定义getter;在store中的计算属性;也会被缓存;当依赖的值发生变化,才会发生改变
                str(state){// state 就是store中的state
                    return state.count%2 === 0?"偶数":"奇数"
                }
            },
            mutations:{
                //vuex更改store中状态的唯一方法就是commit;
                // state: 状态    payload: 载荷  
                increment(state,payload){
                    // 第一个参数接收到当前state,第二个为事件传的参
                    // mutation 这个对象中的函数的第一个参数的实参都是state;
                    // 在mutation的方法中,都是同步事务,不支持异步;
                    state.count += payload;
                }
            },
            actions:{
                addNum({commit},payload){
                    //commit : 就是store上的commit
                    //actions 支持异步,这里面提交一个mutation的动作
                    commit('increment',payload)
                }
            }
        })
        let first = {
            data() {
                return {
                    
                }
            },
            methods: {
                 // 提交的是mutation里面的函数名;用于修改store中的数据
               /*  increment(val){
                    this.$store.commit("increment",val)
                } */
                //...Vuex.mapMutations(['increment'])
                /* ...Vuex.mapMutations({
                    increment:'increment'
                    // 将this.increment()映射成'this.$store.commit("increment")
                }), */
              /* actions的常规写法
                add(val){
                    this.$store.dispatch("addNum",val);
                } */
              
                ...Vuex.mapActions({
                    add:"addNum"
                })
            },
            /* computed: {
                shop(){
                    return this.$store.state.shop
                }
            }, */
            /* VUEx.mapState:将vuex的store中的state数据,映射到当前实例的计算属性上;
            computed:Vuex.mapState(['shop','count']), */
            //对象展开运算符
            computed:{
                //Vuex的私有属性提供了mapState  mapGetters MapMutations;可以将store中的state、getters、mutations都映射当前的实例的computed或methods;这几个函数都会返回一个包装后的对象
                ...Vuex.mapState(['shop','count']),
                ...Vuex.mapGetters(['str'])
            },
            template:"<div>{{this.$store.state.count}} <button @click='add(3)'>++</button> <li v-for='(item, index) in shop'>{{item.name}}</li>{{str}}</div>"
        }
        let second = {
            data() {
                return {
                    
                }
            },
            template:"<div>{{this.$store.state.count}}</div>"
        }
        let vm = new Vue({
            el:"#app",
            data() {
                return {
                    
                }
            },
            components:{
                first,
                second
            },
            store,store // 当前vue的实例就会新增一个$store的属性,属性值时一个对象;同时也会给当前的子组件新增一个$store属性
        })
    </script>
</body>
</html>
//module例子
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <first></first>
        <second></second>
    </div>
    <script src="../../node_modules/vuex/dist/vuex.min.js"></script>
    <script src="../../node_modules/vue/dist/vue.js"></script>
    <script>
        // modues:
        let  moudesA={
            state:{
                a:100
            },
            getters:{
                str1(state,a){
                    return state.a === 99;
                }
            },
        }
        let  moudesB={
            state:{
                num:88
            }
        }
        let store = new Vuex.Store({
            state:{
                count:0
            },
            getters:{
                str(state){
                    return state.count%2===0?"偶数":"奇数";
                }
            },
            mutations:{
                add_count(state,payload){// state: 默认接收一个state
                    state.count+=payload;
                }
            },
            actions:{
               
                add({commit},val){// 提交一个mutations
                    setTimeout(()=>{
                        commit("add_count",val)
                    },1000)
                   
                }
            },
            modules:{
                // 这个modules会把各自模块的state,getters,mutations,actions最终都会注入到该Store中
                first:moudesA,
                second:moudesB
            }
        });
        let first={
            data(){
                return {}
            },
            methods:{
                ...Vuex.mapMutations(["add_count"]),
                addState(val){
                    this.$store.dispatch("add",val);
                }
            },
            computed:{
                ...Vuex.mapGetters(["str"]),
                ...Vuex.mapGetters(['str1'])
            },
            template:"<div>{{$store.state.count}}<button>新增</button>{{str}}{{$store.state.first.a}}{{str1}}</div>"
        }
        let second={
            data(){
                return {}
            },
            template:"<div>{{$store.state.count}}</div>"
        }
        let vm = new Vue({
            el:"#app",
            data:{
            },
            components:{
                first,
                second
            },
            store
        })
    </script>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
是的,在Vuex中,建议使用commit来触发一个mutation。commit是一个用于提交(触发)mutation的方法,它可以在组件中调用。 使用commit的好处有以下几点: 1. 易于管理和维护:通过commit方法调用mutation,可以将状态变更的逻辑封装在mutation中,使代码更加模块化和可维护。 2. 增加代码的可读性:通过使用commit方法,可以清晰地表达组件对应用状态进行某种变更的意图,使代码更易读和理解。 3. 严格控制状态的变更:Vuex核心理念是“单一状态树”,即应用程序的所有状态都集中在一个store中。通过使用commit方法,可以确保只能通过mutations来修改状态,从而保证状态的变更是可追踪和可控制的。 下面是一个使用commit方法触发mutation的示例: ```javascript // 定义一个mutation const mutations = { SET_LOADING(state, isLoading) { state.loading = isLoading; }, SET_DATA(state, data) { state.data = data; }, SET_ERROR(state, error) { state.error = error; }, }; // 在组件中使用commit来触发mutation methods: { setLoading(isLoading) { this.$store.commit('SET_LOADING', isLoading); }, setData(data) { this.$store.commit('SET_DATA', data); }, setError(error) { this.$store.commit('SET_ERROR', error); }, } ``` 在上述示例中,定义了几个名为SET_LOADING、SET_DATA和SET_ERROR的mutations,通过commit方法触发这些mutations来修改应用程序的状态。在组件中,使用this.$store.commit('mutationName', payload)来调用对应的mutation,从而触发状态的变更。其中,payload可以是一个参数,用于传递给mutation进行状态变更的数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值