状态管理Vuex 之 State

  • 原创
  • 作者:程序员三丰
  • 发布时间:2021-08-03 09:50
  • 浏览量:538
store的state,类似于组件的data,我个人把他理解为是一种高级的“全局变量”的解决方案,他能解决跨组件跨页面共享数据的问题,更好地解决了非父子组件的消息传递(也就是将数据存放在state中)。

状态管理Vuex 之 State

State 概念介绍

单一状态树,定义应用状态的默认初始值,页面显示所需的数据从该对象中进行读取。

  • Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。它便作为一个“唯一数据源”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。
  • 单一状态树让我们能够直接定位任一特定的状态片段,在调试过程中也能轻易的取得整个当前应用状态的快照。
  • 不可直接对 state 进行更改,需要通过 Mutation 方法来更改。

注入 state 的两种方式

  • 在页面根节点注入,缺点是需要在每个页面或组件中频繁地导入。

    <!-- 页面路径:pages/index/index.vue -->
    <template>
        <view>
            <text>....</text>
        </view>
    </template>
    <script>
        import store from '@/store/index.js' //需要引入store
        export default {
            data() {
                return {}
            }
        }
    </script>
    
  • 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个组件中。

    • 在 store 目录下新建 index.js 文件

      /* 文件路径:store/index.js */
      import Vue from 'vue'
      import Vuex from 'vuex'
      
      Vue.use(Vuex); // vue的插件机制
      
      //Vuex.Store 构造器选项
      const store = new Vuex.Store({
          state: {
              "username":"Sticker",
              "age":18
          }
      })
      
      export default store
      
    • 在 main.js 中导入文件

      /* 文件路径:main.js */
      import Vue from 'vue'
      import App from './App'
      import store from './store'
      
      Vue.prototype.$store = store
      
      // 把 store 对象提供给 “store” 选项,这可以把 store 的示例注入到所有的子组件
      const app = new Vue({
          store,
          ...App
      })
      
      app.$mount()
      

获取 state

  • 通过属性访问,需要在根节点注入 store。

    <!-- 页面路径:pages/index/index.vue -->
    <template>
        <view>
            <text>用户名:{{username}}</text>
        </view>
    </template>
    <script>
        import store from '@/store/index.js' //需要引入store
        export default {
            data() {
                return {}
            },
            computed: {
                username() {
                    return store.state.username
                }
            }
        }
    </script>
    
  • 在组件中使用,通过 this.$store 访问到 state 里的数据。

    <!-- 组件路径:components/user-info/user-info.vue -->
    <template>
        <view>
            <view>user-info  组件</view>
            <view>真实姓名:{{username}}</view>
        </view>
    </template>
    <script>
        export default {
            name: "user-info",
            data() {
                return {}
            },
            computed: {
                username() {
                    return this.$store.state.username
                }
            }
        }
    </script>
    
  • 通过 mapState 辅助函数获取。

    • 当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,可以使用 mapState 辅助函数帮助我们生成计算属性。

      <!-- 页面路径:pages/index/index.vue -->
      <template>
          <view>
              <view>用户名:{{username}}</view>
              <view>年龄:{{age}}</view>
          </view>
      </template>
      
      <script>
          import { mapState } from 'vuex' //引入mapState
          export default {
              data() {
                  return {}
              },
              computed: mapState({
                  // 从 state 中拿到数据,箭头函数可使代码更简练
                  username: state => state.username,
                  age: state => state.age,
              })
          }
      </script>
      
    • 当映射的计算属性的名称与 state 的子节点名称相同时,可以给 mapState 传一个字符串数组

      <!-- 页面路径:pages/index/index.vue -->
      <template>
          <view>
              <view>用户名:{{username}}</view>
              <view>年龄:{{age}}</view>
          </view>
      </template>
      
      <script>
          import { mapState } from 'vuex' //引入mapState
          export default {
              data() {
                  return {}
              },
              computed: mapState([
                  'username', //映射 this.username 为 store.state.username
                  'age',
              ])
          }
      </script>
      
    • 为了能够使用 this 获取组件自己的 data 数据,必须使用常规函数。

      <!-- 页面路径:pages/index/index.vue -->
      <template>
          <view>
              <view>用户名:{{username}}</view>
              <view>年龄:{{age}}</view>
          </view>
      </template>
      
      <script>
          import { mapState } from 'vuex' //引入mapState
          export default {
              data() {
                  return {
                      tag:"蜀汉"
                  }
              },
              computed: {
                  ...mapState({
                      username: function(state) {
                          return this.tag + ' ' + state.username
                      },
                      age: state => state.age
                  })
              }
          }
      </script>
      
    • 使用对象展开运算符

      mapState 函数返回的是一个对象。使用对象展开运算符将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性,极大简化写法

      <!-- 页面路径:pages/index/index.vue -->
      <template>
          <view>
              <view>用户名:{{username}}</view>
              <view>年龄:{{age}}</view>
          </view>
      </template>
      
      <script>
          import { mapState } from 'vuex' //引入mapState
          export default {
              data() {
                  return {}
              },
              computed: {
                  //使用对象展开运算符将此对象混入到外部对象中
                  ...mapState({
                      username: state => state.username,
                      age: state => state.age
                  }),
                  welcome() {
                      return '欢迎,' + this.username
                  },
              }
          }
      </script>
      

      以上代码都是手写 官方代码,经过运行测试通过的。
      作为程序员,要想学会一门技术,一定不能偷懒,一定要手写运行代码!!!

声明:本文为原创文章,51blog.xyz和作者拥有版权,如需转载,请注明来源于51blog.xyz并保留原文链接:https://www.51blog.xyz/article/18

文章归档

强烈推荐的PHP全栈开发后台管理系统
buildadmin logo
Thinkphp8 Vue3 Element PLus TypeScript Vite Pinia

🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。

推荐文章

热门标签

PHP ThinkPHP ThinkPHP5.1 Go Mysql Mysql5.7 Redis Linux CentOS7 Git HTML CSS CSS3 Javascript JQuery Vue LayUI VMware Uniapp 微信小程序 docker wiki Confluence7 学习笔记 uView ES6 Ant Design Pro of Vue React ThinkPHP6.0 chrome 扩展 翻译工具 Nuxt SSR 服务端渲染 scrollreveal.js ThinkPHP8.0 Mac webman 跨域CORS vscode GitHub ECharts Canvas vue3 three.js 微信支付 PHP全栈开发 Python AI 人工智能 AI辅助 工作经验 实战笔记