js 操作vuex数据_vue--vuex详解

Vuex是一个用于管理Vue.js应用中组件状态的库。它提供集中式存储来处理组件间通信,简化大型项目的状态管理。通过Vuex,可以使用state存储共享数据,mutations进行同步状态变更,getters获取数据,以及actions处理异步操作。在组件中,通常通过计算属性来响应式地获取state数据。
摘要由CSDN通过智能技术生成

Vuex

    什么是Vuex?

       官方说法:Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

      个人理解:Vuex是用来管理组件之间通信的一个插件

    为什么要用Vuex?

      我们知道组件之间是独立的,组件之间想要实现通信,我目前知道的就只有props选项,但这也仅限于父组件和子组件之间的通信。如果兄弟组件之间想要实现通信呢?嗯..,方法应该有。抛开怎么实现的问题,试想一下,当做中大型项目时,面对一大堆组件之间的通信,还有一大堆的逻辑代码,会不会很抓狂??那为何不把组件之间共享的数据给“拎”出来,在一定的规则下管理这些数据呢? 这就是Vuex的基本思想了。

    Vuex有什么特性?

    怎么使用Vuex?

      引入Vuex.js文件

      创建实例:

<!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>
<script src="./js/vuex.js"></script>
<script src="./js/vue2.0.js"></script>
<body>
    <div id="app">
        
    </div>
</body>
<script>
    Vue.use(Vuex);//在创建Vue实例之前
   var myStore =  new Vuex.Store({
        state:{
            //存放组件之间共享的数据
            name:"jjk"
        },
         mutations:{
             //显式的更改state里的数据
         },
         getters:{
             //获取数据的方法
         },
         actions:{
             //
         }
    });
    new Vue({
        el:"#app",
        data:{
            name:"dk"
        },
        store:myStore,
        mounted:function(){
            console.log(this)//控制台
        }
    })
</script>
</html>

 先解释上面代码的意思:

    new Vuex.Store({}) 表示创建一个Vuex实例,通常情况下,他需要注入到Vue实例里. Store是Vuex的一个核心方法,字面上理解为“仓库”的意思。Vuex Store是响应式的,当Vue组件从store中读取状态(state选项)时,若store中的状态发生更新时,他会及时的响应给其他的组件(类似双向数据绑定) 而且不能直接改变store的状态,改变状态的唯一方法就是,显式地提交更改(mutations选项)

他有4个核心选项:state mutations getters actions (下文会仔细分析)

  这是上面代码:

4e7a70bac7cbc753314e8d28149d8727.png

那如何获取到state的数据呢?

    一般会在组件的计算属性(computed)获取state的数据(因为,计算属性会监控数据变化,一旦发生改变就会响应)

<!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>
<script src="./js/vuex.js"></script>
<script src="./js/vue2.0.js"></script>
<body>
    <div id="app">
        <hello></hello>
    </div>
</body>
<script>
    Vue.use(Vuex);
   var myStore =  new Vuex.Store({
        state:{
            //存放组件之间共享的数据
            name:"jjk"
        },
         mutations:{
             //显式的更改state里的数据
         },
         getters:{
             //过滤state数据
         },
         actions:{
             //
         }
    });

    Vue.component('hello',{
        template:"<p>{{name}}</p>",
        computed: {
            name:function(){
                return this.$store.state.name
            }
        },
         mounted:function(){
            console.log(this)
        }
    })
    new Vue({
        el:"#app",
        data:{
            name:"dk"
        },
        store:myStore,
        mounted:function(){
            console.log(this)
        }
    })
</script>
</html>

a9c1c6d52bec3ddb91e1e9f055fd0617.png

state:用来存放组件之间共享的数据。他跟组件的data选项类似,只不过data选项是用来存放组件的私有数据。

  getters:有时候,我们需要对state的数据进行筛选,过滤。这些操作都是在组件的计算属性进行的。如果多个组件需要用到筛选后的数据,那我们就必须到处重复写该计算属性函数;或者将其提取到一个公共的工具函数中,并将公共函数多处导入 - 两者都不太理想。如果把数据筛选完在传到计算属性里就不用那么麻烦了,getters就是干这个的,你可以把getters看成是store的计算属性。getters下的函数接收接收state作为第一个参数。那么,组件是如何获取经过getters过滤的数据呢? 过滤的数据会存放到$store.getters对象中。具体看一个例子:<!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>
<script src="./js/vuex.js"></script>
<script src="./js/vue2.0.js"></script>
<body>
    <div id="app">
        <hello></hello>
    </div>
</body>
<script>
    Vue.use(Vuex);
   var myStore =  new Vuex.Store({
        state:{
            //存放组件之间共享的数据
            name:"jjk",
            age:18
        },
         mutations:{
             //显式的更改state里的数据
         },
         getters:{
             getAge:function(state){
                 return state.age;
             }
         },
         actions:{
             //
         }
    });

    Vue.component('hello',{
        template:"<p>姓名:{{name}} 年龄:{{age}}</p>",
        computed: {
            name:function(){
                return this.$store.state.name
            },
            age:function(){
                return this.$store.getters.getAge
            }
        },
         mounted:function(){
            console.log(this)
        }
    })
    new Vue({
        el:"#app",
        data:{
            name:"dk"
        },
        store:myStore,
        mounted:function(){
            console.log(this)
        }
    })
</script>
</html>

288f6320176e3e896dec9ff20db45289.png

 mutations:前面讲到的都是如何获取state的数据,那如何把数据存储到state中呢?在 Vuex store 中,实际改变 状态(state) 的唯一方式是通过 提交(commit) 一个 mutation。  mutations下的函数接收state作为参数,接收一个叫做payload(载荷)的东东作为第二个参数,这个东东是用来记录开发者使用该函数的一些信息,比如说提交了什么,提交的东西是用来干什么的,包含多个字段,所以载荷一般是对象(其实这个东西跟git的commit很类似)还有一点需要注意:mutations方法必须是同步方法

  具体看实例:

<!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>
<script src="./js/vuex.js"></script>
<script src="./js/vue2.0.js"></script>
<body>
    <div id="app">
        <hello></hello>
    </div>
</body>
<script>
    Vue.use(Vuex);
   var myStore =  new Vuex.Store({
        state:{
            //存放组件之间共享的数据
            name:"jjk",
            age:18,
            num:1
        },
         mutations:{
             //显式的更改state里的数据
             change:function(state,a){
                //  state.num++;
               console.log(state.num += a); 
               
             }
         },
         getters:{
             getAge:function(state){
                 return state.age;
             }
         },
         actions:{
             //
         }
    });

    Vue.component('hello',{
        template:"<p @click='changeNum'>姓名:{{name}} 年龄:{{age}} 次数:{{num}}</p>",
        computed: {
            name:function(){
                return this.$store.state.name
            },
            age:function(){
                return this.$store.getters.getAge
            },
            num:function(){
                return this.$store.state.num
            }
        },
         mounted:function(){
            console.log(this)
        },
        methods: {
            changeNum: function(){
                //在组件里提交
                // this.num++;
                this.$store.commit('change',10)
            }
        },
        data:function(){
            return {
                // num:5
            }
        }
    })
    new Vue({
        el:"#app",
        data:{
            name:"dk"
        },
        store:myStore,
        mounted:function(){
            console.log(this)
        }
    })
</script>
</html>

相信很多人在刚接触前端或者中期时候总会遇到一些问题及瓶颈期,如学了一段时间没有方向感或者坚持不下去一个人学习枯燥乏味有问题也不知道怎么解决,对此我整理了一些资料 喜欢我的文章想与更多资深大牛一起讨论和学习的话 欢迎加入我的学习交流群

→点这里​jq.qq.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序中管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集中的存储库中,称为store。Vuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store中获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序中使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件中使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例中,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store中获取count状态。在Vue组件中,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值