Vuex中的state属性详解

一、state属性介绍

state属性是Vuex中用于存放组件之间共享的数据;也就是说,我们把一些组件之间共享的状态主要存放在state属性中;它采用的是单一状态树——用一个对象就包含了全部的应用层级状态。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。

二、state的使用

  • 在HTML中我们可以直接省略 this 关键字 ,直接使用 $store.state.状态名(变量名) 来访问 vuex 中的存储的状态;

① 抽离出去的state.js文件

export default {
    
    
  loadingFlag: true,
  // 用于保存已选类别标签
  changedLableList: [
    {
    
     name: '头条', class: 'iconfont icon-jinrishouru', url: 'topnews/index' },
    {
    
     name: '苹果', class: 'iconfont icon-pingguoapple', url: "apple/index" },
    {
    
     name: 'NBA', class: 'iconfont icon-tiyu-lanqiu', url: "nba/index" },
    {
    
     name: '创业', class: 'iconfont  icon-chaxunchuangyebankaitongqingkuang', url: "startup/index" },
    {
    
     name: '足球', class: 'iconfont icon-swticonzuqiu', url: "football/index" },
    {
    
     name: '体育', class: 'iconfont icon-paobu', url: "tiyu/index" }
  ]
}

② 在index.js文件中导入state.js文件并注册

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import state from './state'
import actions from './actions'
import getters from './getters'

// 安装插件
Vue.use(Vuex)

// 创建对象
export default new Vuex.Store({
    
    
  state,
  mutations,
  actions,
  getters
})

③ 在组件中使用

<div class="flex-content">
          <div class="lable-items" v-for="(item, index) in $store.state.changedLableList" :key="index" @click="decrementTypeLable(index)">
            <div class="item">
              <div><i :class="item.class"></i></div>
              <span>{
    
    {
    
     item.name }}</span>
            </div>
          </div>
        </div>
  • 在js代码中,必须使用 this.$store.state.状态名(变量名) 来访问vuex中存储的状态;
computed: {
    
    
    title() {
    
    
      return this.$route.meta.title
    },
    changedLableList() {
    
    
      return this.$store.state.changedLableList
    },
    alternativeLableList() {
    
    
      return this.$store.state.alternativeLableList
    }
  },

三、扩展

为什么要在组件的computed计算属性中使用不能放到data属性中?

data 中的内容只会在 created 钩子函数触发前初始化一次,类似于我们直接写 const data = { foo: 123 }这样,这时属性的值是纯粹的字面量,而不是所谓的【缓存】(没有 Cache Miss 哪来的缓存?)。JS字面量赋值后显然不会自动更新。最简单的例子:
let b = ‘xxx’ // 相当于state中的数据
let a = b // 相当于data初始化时,将b的值赋值给了a
b = ‘xyz’ // 这时对于原始类型,a 肯定还是 ‘xxx’
换句话说,data 中内容依赖变更时,data 属性不会变更(它的设计目标就是保存组件的局部状态数据而已)。而 computed则是通过【依赖追踪】实现的,在 computed 求值时引用的 Vue 变量变化时,会触发对 computed 的重新计算。所以我们可以使用computed 去引用 Vuex 状态变量,从而使得依赖追踪生效。或者,将 Vuex 状态变量通过 mapState() 方法映射为 computed 也是一个很方便的选择。

猜你喜欢

转载自blog.csdn.net/qq_40117020/article/details/108264309