Vuex-核心概念 - state

  • 核心概念 - state

1. 核心概念 - state

1.目标

明确如何给仓库 提供 数据,如何 使用 仓库的数据

2.提供数据

State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。

打开项目中的store.js文件,在state对象中写我们要的数据。

// 创建仓库 store
const store = new Vuex.Store({
  // state 状态, 即数据, 类似于vue组件中的data,
  // 区别:
  // 1.data 是组件自己的数据, 
  // 2.state 中的数据整个vue项目的组件都能访问到
  state: {
    count: 101
  }
})

3.访问Vuex中的数据

问题: 如何在组件中获取count?

  1. 通过$store直接访问 —> {{ $store.state.count }}
  2. 通过辅助函数mapState 映射计算属性 —> {{ count }}

4.通过$store访问的语法

获取 store:
 1.Vue模板中获取 this.$store
 2.js文件中获取 import 导入 store


模板语法:     {{ $store.state.xxx }}
组件逻辑中:  this.$store.state.xxx
JS模块中:   store.state.xxx

5.代码实现

5.1模板中使用

组件中可以使用 $store 获取到vuex中的store对象实例,可通过state属性属性获取count, 如下

<h1>state的数据 - {{ $store.state.count }}</h1>

5.2组件逻辑中使用

将state属性定义在计算属性中 https://vuex.vuejs.org/zh/guide/state.html

<h1>state的数据 - {{ count }}</h1>

// 把state中数据,定义在组件内的计算属性中
  computed: {
    count () {
      return this.$store.state.count
    }
  }

5.3 js文件中使用

//main.js

import store from "@/store"

console.log(store.state.count)

每次都像这样一个个的提供计算属性, 太麻烦了,我们有没有简单的语法帮我们获取state中的值呢?

7辅助函数 mapState

用法 :1.第一步:导入mapState (mapState是vuex中的一个函数)

import { mapState } from 'vuex'

2.第二步:采用数组形式引入state属性

mapState(['count']) 

上面代码的最终得到的是 类似于

count () {
    return this.$store.state.count
}

3.第三步:利用展开运算符将导出的状态映射给计算属性

  computed: {
    ...mapState(['count'])
  }
 <div> state的数据:{{ count }}</div>
posted @ 2024-07-25 17:40  AAA晚来秋  阅读(90)  评论(0)    收藏  举报