Vue 教程(四十九)Vuex 核心概念和项目结构
Vuex 核心概念
- State
- Getters
- Mutations
- Actions
- Modules
State 单一状态树
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 ”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。
new Vue({
// state
data() {
return {
count: 0,
}
},
// view
template: `
<div>{
{ count }}</div>
`,
// actions
methods: {
increment() {
this.count++
},
},
})
Getters
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
-
配置 vuecli2\src\store\index.js 文件
import Vue from 'vue' import Vuex from 'vuex' // 1.安装插件 Vue.use(Vuex) // 2. 创建对象 const store = new Vuex.Store({ state: { counter: 1000, goods: [ { id: 1, name: '[五得利]高筋小麦粉', price: 92.9 }, { id: 2, name: '新鲜莲藕(泥藕) 约600g', price: 6.8 }, { id: 3, name: '香菜 约100g', price: 1.39 }, { id: 4, name: '益客冷鲜鸡翅中 400g', price: 21.9 }, { id: 5, name: '进口原切冷冻牛腩 400g', price: 31.8 }, { id: 6, name: '多力葵花籽油 5L/桶(另送小油)', price: 79.9 }, ], }, mutations: { // 对state.counter属性每次+1操作 increment(state) { state.counter++ }, // 对state.counter属性每次-1操作 decrement(state) { state.counter-- }, }, getters: { // state 作为第一个参数 queryGoods(state) { // 要求筛选价格大于 30 的商品。 return state.goods.filter((g) => g.price > 30) }, queryGoodsCount(state, getters) { // 筛选价格大于 30 的商品 的个数 return getters.queryGoods.length }, queryGoodsById(state) { // 根据商户id获取商品 return function (id) { return state.goods.find((g) => g.id === id) } }, }, }) // 3. 导出store独享 export default store
- 修改 vuecli2\src\App.vue 文件
<template> <div id="root"> <div> 计数器: <button @click="addition()">+</button> <button @click="subtraction()">-</button> </div> <div class="layout">