如何使用vuex操作state对象

js教程评论2.1K views阅读模式

这次给大家带来如何使用vuex操作state对象,使用vuex操作state对象的注意事项有哪些,下面就是实战案例,一起来看一下。

Vuex是什么?

VueX 是一个专门为 Vue.js 应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。

Vue有五个核心概念,state, getters, mutations, actions, modules。

总结

state => 基本数据
getters => 从基本数据派生的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
modules => 模块化Vuex

State

state即Vuex中的基本数据!

单一状态树

Vuex使用单一状态树,即用一个对象就包含了全部的状态数据。state作为构造器选项,定义了所有我们需要的基本状态参数。

在Vue组件中获得Vuex属性

•我们可以通过Vue的Computed获得Vuex的state,如下:

const store = new Vuex.Store({
  state: {
    count:0
  }
})
const app = new Vue({
  //..
  store,
  computed: {
    count: function(){
      return this.$store.state.count
    }
  },
  //..
})

下面看下vuex操作state对象的实例代码

每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

每一个 Vuex 应用的核心就是 store(仓库)。

引用官方文档的两句话描述下vuex:

1,Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

2,你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

使用vuex里的状态

1,在根组件中引入store,那么子组件就可以通过this.$store.state.数据名字得到这个全局属性了。

我用的vue-cli创建的项目,App.vue就是根组件

App.vue的代码

<template>
 <p id="app">
   <h1>{{$store.state.count}}</h1>  
  <router-view/>
 </p>
</template>
<script>
 import store from '@/vuex/store';
export default {
 name: 'App',
 store
}
</script>
<style>
</style>

在component文件夹下Count.vue代码

<template>
 <p>
   <h3>{{this.$store.state.count}}</h3>
 </p>
</template>
<script> 
  export default {
    name:'count',
  }
</script>
<style scoped>
</style>

store.js的代码

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state = {
 count: 1
}
export default new Vuex.Store({
 state,
})

2,通过mapState辅助函数得到全局属性

这种方式的好处是直接通过属性名就可以使用得到属性值了。

将Component.vue的代码进行改变

<template>
 <p>
   <h3>{{this.$store.state.count}}--{{count}}</h3>
  <h4>{{index2}}</h4>
 </p>
</template>
<script> 
  import { mapState,mapMutations,mapGetters } from "vuex";
  export default {
    name:'count',
    data:function(){
      return {
        index:10
      }
    },
    //通过对象展开运算符vuex里的属性可以与组件局部属性混用。
    computed:{...mapState(['count']),
      index2() {
        return this.index+30;
      }  
    } ,
  }
</script>
<style scoped>
</style>

相信看了本文案例你已经掌握了方法,更多精彩请关注php教程其它相关文章!

推荐阅读:

怎样对vue文件进行解析

如何优化Vue

以上就是如何使用vuex操作state对象的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2019年9月12日 21:34:19
  • 转载请务必保留本文链接:https://www.qieseo.com/403232.html

发表评论