Vuex数据存储与获取

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vuex数据存储与获取

Vc编码中   2022-06-28 我要评论

Vuex数据存储与获取

因为最近需要对原有项目进行改造,之前没有认真研究过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里 

Vuex存值与取值(简单易懂)

组件内存值

methods: {  
     fn() {     
             this.$store.commit('setValue',xxx)   //setValue存值随便起个名,   xxx要存的值 
          }           
    }

store.js的state中

const state = {
    xxx:'',//把存的那个值的名字初始化一下
}

store.js的matution中

  setValue(state,item){
    state.xxx= item;//第二个参数随意起个名
  },

组件内取值

//在计算属性中取值,js直接这样写拿到值,html用直接xxx使用
 computed: {    
    value() {
      return this.$store.state.xxx;
    }
  },

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们