[Vuex系列] - 细说state的几种用法

state 存放的是一个对象,存放了所有的应用层级的状态,主要是存放咱们平常使用的组件之间传递的变量。vue

咱们今天重点讲解下state的几种用法,至于如何从头开始建立Vuex项目,请看我写的第一个文章。点击查看vuex

用法一:使用this.$store

咱们仍是以一个累加器的例子来看如何实现,具体实现代码以下:bash

在state.js文件中添加一个count的变量模块化

const state = {
  count: 0
}
export default state
复制代码

在src文件夹下新建一个state文件夹,并新建index.vue文件,文件内容以下:函数

<template>
  <div class="state">
    <h2>{{ count }}</h2>
    <button @click="add">+ADD</button>
  </div>
</template>

<script>
export default {
  computed: {
    count () {
      // 第一种用法
      return this.$store.state.count
    }
  },
  methods: {
    add () {
      // 第一种用法
      this.$store.state.count++
    }
  }
}
</script>

复制代码

在Vue根实例中注册了store选项,该store实例会注入到根组件下的全部子组件中,且子组件能经过 this.$store 访问到。post

用法二:引用store.js文件

具体实现代码以下:ui

state.js文件内容参考上面的例子,修改state/index.vue,内容以下:this

<template>
  <div class="state">
    <h2>{{ count }}</h2>
    <button @click="add">+ADD</button>
  </div>
</template>

<script>
import store from '@/store/store.js'
export default {
  computed: {
    count () {
      // 第二种用法
      return store.state.count
    }
  },
  methods: {
    add () {
      // 第二种用法
      store.state.count++
    }
  }
}
</script>

复制代码

这种方法在Vue的模块化的构建系统中,在每一个须要使用state的组件中须要频繁地导入。spa

用法三:使用mapState辅助函数

具体实现代码以下:code

state.js文件内容参考上面的例子,修改state/index.vue,内容以下:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
  </div>
</template>

<script>
// import store from '@/store/store.js'
import { mapState } from 'vuex'
export default {
  computed: mapState({
    count: state => state.count
  })
}
</script>

复制代码

<template>
  <div class="state">
    <h2>{{ count }}</h2>
  </div>
</template>

<script>
// import store from '@/store/store.js'
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['count'])
  }
}
</script>
复制代码

当一个组件须要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,咱们可使用 mapState 辅助函数帮助咱们生成计算属性


1、[Vuex系列] - 初尝Vuex第一个例子

2、[Vuex系列] - 细说state的几种用法

3、[Vuex系列] - Mutation的具体用法

4、[Vuex系列] - getters的用法

5、[Vuex系列] - Actions的理解之我见

6、[Vuex系列] - Module的用法(终篇)

相关文章
相关标签/搜索