state 存放的是一个对象,存放了所有的应用层级的状态,主要是存放咱们平常使用的组件之间传递的变量。vue
咱们今天重点讲解下state的几种用法,至于如何从头开始建立Vuex项目,请看我写的第一个文章。点击查看vuex
咱们仍是以一个累加器的例子来看如何实现,具体实现代码以下: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
具体实现代码以下: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
具体实现代码以下: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 辅助函数帮助咱们生成计算属性