0
点赞
收藏
分享

微信扫一扫

Vuex状态管理模式详细说明及使用示例

简述

安装依赖

方式一: CDN

<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

方式二:NPM

npm install vuex --save

方式三:Yarn

yarn add vuex

配置说明

全局配置及使用

  • state属性:单一状态树,用一个对象就包含了全部的应用层级状态
    1.在src下创建文件夹store/index.js,始化设置两个状态
// 第一步:引入Vue、和Vuex(固定写法)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

// 第二步:声明Vuex 的五个属性,其中state,mutations 是一定要定义的,其他的三个属性对象根据实际需要。
const state = {  // 初始化状态值--一定要有该属性对象
    num:3, // 初始化一个状态,存放学生人数
    name:[ // 初始化一个状态,存放学生的分数信息
           {name:'张三',score:9999},
           {name:'李思',score:9880},
           {name:'小明',score:97778}
       ]
}
 // 自定义改变state初始值的方法--一定要有该属性对象
// const mutations = {
//     ...
// }
// 状态计算属性--该属性对象不是必须的
// const getters = {
//     ...
// }
// 异步操作状态--该属性对象不是必须的
// const actions = {
//     ...
// }
// 状态模块--该属性对象不是必须的
// const modules = {
//     ...
// }

// 第三步:创建一个 store 实例,将声明的五个变量赋值赋值给 store 实例,如下:
const store = new Vuex.Store({
   state,
   // mutations,
    //下面三个非必须
   // getters,
   // actions,
   // modules
})

// 第四步:导出 store 实例,供外部访问
export default store

2.创建一个测试组件TestVuex,在组件中获取两个状态的值

<template>
<div>
  <div class="demo1">
    <h4>直接使用状态值—— <span>人数:{{$store.state.Num}}</span></h4>
    <p v-for="(item,index) in $store.state.Stud" :key="index">
      姓名:{{item.name}} | 总数:{{item.score}}
    </p>
  </div>

  <div class="demo2">
    <h4>通过计算属性获取—— <span>人数:{{StudNum}}</span></h4>
    <p v-for="(item,index) in StudScore" :key="index">
      姓名:{{item.name}} | 总数:{{item.score}}
    </p>
  </div>
</div>
</template>

<script>
export default {
  computed: { // 计算属性
    StudNum() {
      return this.$store.state.Num
    },
    StudScore() {
      return this.$store.state.Stud
    },
  }
}
</script>

<style lang="less" scoped>
div{
  text-align: center;
  margin: 0px;
  padding: 0px;
  border: 1px solid #B3C0D1;

  .demo1{
    background-color:#b7ceff;
    h4{
      margin-top: 50px;
    }
  }
  .demo2{
     background-color:#ffdcfc;
  }
}
</style>

3.效果图


  • mapState 辅助函数
 <div class="demo3">
      <h4>mapState通过计算属性获取—— <span>人数:{{Count}}</span></h4>
      <p v-for="(item,index) in User" :key="index">
        姓名:{{item.name}} | 总数:{{item.score}}
      </p>
    </div>

<script>
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
    data(){
        return{
         localCount:12
        }
    },
       computed: mapState({
            Count: state => state.Num,  // 箭头函数可使代码更简练
            User: 'Stud',           // 可也传字符串参数 'User' 等同于 `state =>state.Stud
            nweNum(state) {  // 为了能够使用 `this` 获取局部状态,必须使用常规函数纠正this指向
                return state.count + this.localCount
            }
        })
}
</script>
computed: mapState([
  'Num',   // 映射 this.Num为 this.$store.state.Num
  'Stud'  // 映射 this.Stud为 this.$store.state.Stud
])
    computed: { // 计算属性
      StudNum() {
        return this.$store.state.Num
      },
      StudScore() {
        return this.$store.state.Stud
      },
      ...mapState({
            Count: state => state.Num,  // 箭头函数可使代码更简练
            User: 'Stud',           // 可也传字符串参数 'StudScore' 等同于 `state =>state.StudScore
            nweNum(state) {  // 为了能够使用 `this` 获取局部状态,必须使用常规函数纠正this指向
                return state.count + this.localCount
            }
        })
    }

最终全部显示效果

  • Getter属性的使用
getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

示例1:getter 通过属性访问
在上面创建的store/index中添加如下:

const getters = {
    // 获取分数为777分以上的学生
       perfect: state => { // 过滤分数,获取777分及以上的学生
           return state.Stud.filter(Stud => Stud.score>=777)
       },
       // 获取分数为777分以上的学生数量
       perfectNum: (state,getters) => { // getters 也可以接受其他 getters 作为第二个参数
           return getters.perfect.length
       }
}

const store = new Vuex.Store({
   state,
   // mutations,
    //下面三个非必须
   getters,
   // actions,
   // modules
})

组件中添加如下:

<div>
 <h4>getters 派生的状态 通过属性访问</h4>
      <p>大于等于777总数的人数:{{$store.getters.perfectNum}}</p>
      <p v-for="(item,index) in $store.getters.perfect" :key="index">
        姓名:{{item.name}} | 总数:{{item.score}}
      </p>
    </div>

示例2:getter 通过方法访问
在store/index.js中getter 里添加

// 用总数查询信息
  checkScore: state => n => { // 返回一个方法函数
    return state.Stud.find(Stud => Stud.score === n)
  }
<div>
<h4>getters 派生的状态 通过方法访问</h4>
        <p>有没有人得777分</p>
        <p>{{$store.getters.checkScore(777)}}</p>
</div>


更多详情Vuex

举报

相关推荐

0 条评论