vue 中数据流 状态的简单介绍

来源:互联网 发布:Linux 子系统 编辑:程序博客网 时间:2024/05/17 01:30

vuex

在已下的文档中使用到 es6/es5语法 记得熟悉下 es5官网

如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)

vuex核心概念

const store = new Vuex.Store({  state:{    ...  },  mutations:{    ...  },  actions:{    ...  },  getters:{    ...  }})

当我们需要管理的状态太多时怎么办那?
这里写图片描述

下面是我具体在项目中的store

这里写图片描述

const store = new Vuex.Store({  state: {    count: 0  },  mutations: {    increment (state) {      state.count++    }  }})

现在,你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:

store.commit('increment')  //驱动 store > mutations > increment 方法 从而使 state > count 发生变化console.log(store.state.count) // -> 1  获取 store > state > count中的值

Vuex 使用 单一状态树 —— 是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个『唯一数据源(SSOT)』而存在。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。但是自从有了对象展开运算符(现处于 ECMASCript 提案 stage-3 阶段),我们可以极大地简化写法:

computed: {  localComputed () { /* ... */ },  //localComputed 此类是申明方法  具体的使用案例 下文中会提及到  // 使用对象展开运算符将此对象混入到外部对象中  ...mapState({    // ...mapState  具体查看es5文档   详细阅读    // ...  })}

下面是项目结构,这是在vue官网call的一份

├── index.html├── main.js├── api│   └── ... # 抽取出API请求├── components│   ├── App.vue│   └── ...└── store    ├── index.js          # 我们组装模块并导出 store 的地方    ├── actions.js        # 根级别的 action    ├── mutations.js      # 根级别的 mutation    └── modules        ├── cart.js       # 购物车模块        └── products.js   # 产品模块