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

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

猜你喜欢

转载自www.cnblogs.com/wangshucheng/p/11203152.html