2021-09-25 vuex 简单使用

一、介绍

Vuex 是一个专为 Vue.js 应用程序开发的\color{red} {状态管理模式}。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

二、安装

    1. cnpm install vuex -S

三、使用

  • 流程图


    1632576905(1).png
  • 使用demo
    1)新建文件 stroe.js
    分四步
    a、导入相关的模块
    b、使用vuex
    c、创建store
    d、导出store

//导入相关的模块
import Vue from "vue"
import Vuex from "vuex"
//使用vuex
Vue.use(Vuex);
//创建store
const store=new Vuex.Store({
   state:{
     count:100
   },
   mutations:{
     increment(state){
       state.count++;
     },
     reducecount(state)
     {
       state.count--;
     }
   },
   getters:{
     count(state){
       return state.count;
     }
   } ,
 actions:{
    increment({commit}){
      commit("increment")
    },
    reducecount({commit}){
      commit("reducecount")
    }
  }
});
//导出store
export default store
  1. store中的核心概念
  • state
  • getters
  • mutations
  • actions
  1. App.vue 中的使用
    注意事项 在使用mapGetters时
    首先得导入
    import {mapGetters} from 'vuex'
    在使用mapGetters 时记得前面有'...' 否则这就是个computed 中的普通方法
 computed:{
    //方式一
    // count:function(){
    //   return this.$store.getters.count;
    // },
    //方式二
    ...mapGetters(['count'])
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容