Vuex数据的存储与获取

本文记录了学习Vuex的过程,重点探讨Vuex的store如何存储响应式state,并通过commit进行状态变更。文章提供了创建store、在组件中提交mutation、在computed属性中获取state、使用mapState辅助函数以及在实际项目中的应用示例,强调了简单逻辑在mutation中,复杂逻辑在actions中的原则。

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

因为最近需要对原有项目进行改造,之前没有认真研究过vuex的使用,今天把学习官方文档的过程记录下来以供日后查阅,同时也希望能够为其他开发人员提供参考。

vuex的核心点是store,store本质上是一个仓库,它可以存储大部分的state。而这种存储是响应式的,如果state发生变化,那么对应的组件也会响应更新。如果想要改变state,那么需要通过commit mutation。

以下示例引用自官网(开始 | Vuex):

// 创建一个新的 store 实例
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

创建完成后可在vue组件中可以以this.$store.commit('具体mutation方法')来提交状态变更

然后通过this.$store.state.x具体某一statex来得到对象的内容。

如果想要更简便的从store实例中读取状态,可以直接在computed中返回某个状态:

// 创建一个 Counter 组件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return store.state.count
    }
  }
}

但是为了避免多次出发dom,vue插件可以将store实例从跟组件中注入到所有的子组件中,子组件可以通过$store访问。

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

当我们需要的状态为多个时,可以利用mapState来生成计算属性

computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}

可以举一个实际应用的例子:

首先在main.js中注册

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
//存放全局状态
state:{
count:0
},

//getters是对state的加工包装,比如将一些数据进行过滤等,为只读的方法,通过return获取值
getters:{
countNum(state){
return `the account NUm is ${state.count}`
}
}

//通过mutations修改state,如果直接修改state会导致一些特性丢失
mutations:{
 add(state){
state.count++
},
 minus(state){
state.count--
}


}


//actions涉及业务逻辑,不涉及页面的一些行为

})

在对应的vue组件中,如下代码可在页面显示count的值,则可在vue的一个组件例如app.vue中进行如下操作

<template>

<div>
<h1>{{count}}</h1>

<h2>{{countNum}} </h2>
</div>

</template>


<script>

import {mapState,mapGetters} from 'vuex'

export default{

//
computed:{
...mapState(['count'])
...mapGetters{['countNum']}
}
}

</script>

若想使用mutation中的方法,则可在另一个vue文件例如hello.vue中进行如下操作,同时为了方便观察,在控制台中可以选择vuex实时观察vue内容

<template>
<div>
<button @click=addnum>增加</button>
</div>

</template>

methods:{
...mapMutations('add','minus')
addnum(){
//mutations必须通过commit才能使用,但是因为之前调用了...mapMutations,所以可以直接调用this.add();
//this.$store.commit('add')
this.add()

//使用mutations会确保有vuex状态改变的记录,如果直接this.$store.state.count也会生效
//this.$store.state.count++但是此种写法开发工具vuex里面无法产生记录
}
}

<javascript>
</javascript>

一般情况下,简单的业务逻辑要写在mutation里,复杂的业务逻辑要写在actions里

ref:开始 | VuexVue.js 的中心化状态管理方案https://vuex.vuejs.org/zh/guide/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值