• 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
  • 相关阅读:
    LostRoutes项目日志——玩家飞机精灵Fighter解析
    quartz Cron表达式一分钟教程
    vue-cli入门
    SQL中merge into用法
    SQLSERVER查询那个表里有数据
    C#实现复杂XML的序列化与反序列化
    MVC和WebApi 使用get和post 传递参数。
    项目管理软件推荐
    JS跨域请求
    Android动画效果translate、scale、alpha、rotate详解
  • 原文地址:https://www.cnblogs.com/1955/p/10018867.html
Copyright © 2020-2023  润新知