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

栏目: JavaScript · 发布时间: 6年前

内容简介:state 存放的是一个对象,存放了全部的应用层级的状态,主要是存放我们日常使用的组件之间传递的变量。我们今天重点讲解下state的几种用法,至于如何从头开始创建Vuex项目,请看我写的第一个文章。点击查看我们还是以一个累加器的例子来看如何实现,具体实现代码如下:

state 存放的是一个对象,存放了全部的应用层级的状态,主要是存放我们日常使用的组件之间传递的变量。

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

用法一:使用this.$store

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

在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 访问到。

用法二:引用store.js文件

具体实现代码如下:

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

<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的组件中需要频繁地导入。

用法三:使用mapState辅助函数

具体实现代码如下:

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 辅助函数帮助我们生成计算属性


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Designing Data-Intensive Applications

Designing Data-Intensive Applications

Martin Kleppmann / O'Reilly Media / 2017-4-2 / USD 44.99

Data is at the center of many challenges in system design today. Difficult issues need to be figured out, such as scalability, consistency, reliability, efficiency, and maintainability. In addition, w......一起来看看 《Designing Data-Intensive Applications》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具