zoukankan      html  css  js  c++  java
  • vuex的状态管理模式

    1、store.js

    Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)

    state:存放数据。

    mutations:提交状态修改,这是vuex中唯一修改state的方式

    var store = new Vuex.Store({
        state: {
            User: {},
        },
        mutations: {
            increment: function (state, user) {
                state.User = user
            },
        }
    }

    2、通过 store.commit 方法触发状态变更

    store.commit('increment', result.data)
    this.$store.commit('increment', result.data)

    3、通过 store.state 来获取状态对象

    console.log(store.state.User)

     4、mapState 辅助函数

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

    1)引用

    import { mapState } from 'vuex'

    2)用法

    // 以数组的方式传入
    computed: mapState([
      'count',
      'orderList'   // 将this.orderList 映射为 store.state.orderList
    ])
    
    // 以对象的方法传入
    computed: mapState({
      count: state => state.count  //直接映射到state 对象中的count, 它相当于 this.$store.state.count,
    })

    mapState通过扩展运算符将store.state.orderList 映射this.orderList  这个this 很重要,这个映射直接映射到当前Vue的this对象上

    3)vue中调用  

    let _this=this;
    let orderList=_this.orderList;
    let count=_this.count
  • 相关阅读:
    阅读 Android源码的一些姿势
    Unity3d UGUI 界面适配 实例解析 三种适配方式
    Unity3D Android手机开发环境配置
    DOTween教程
    DoTween 部分中文文档
    C# 委托、事件,lamda表达式
    EditText中输入信息的限制的方法
    Android中shape中的属性大全
    Android 高版本API方法在低版本系统上的兼容性处理
    python 绘制f(x)=x^2
  • 原文地址:https://www.cnblogs.com/1955/p/10018867.html
Copyright © 2011-2022 走看看