Vuex的用法

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

个人理解:就是在项目中可以对在state中定义的变量,不同的组件之间可以互相使用及修改的目的

npm

npm install vuex --save

Yarn

yarn add vuex

创建store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

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

Store状态管理中有2个方法 mutations 和 actions
2个方法都能管理改变state中的值,actions 可以异步操作

在外部引用这个state
需要在 计算属性中获取state 的值 通过 this.$store.state.值得名称

state需要在 computed 取值

Computed:{
   Abc(){
     Return this.$store.state.值得名称
   }
}
在div中 直接应用{{Abc}} 即可获取state中的值
 
{{Abc}}
如果需要在该组件中对其值 进行改变 需要通过以下方法来操作实现state值得更改
image.png

如果没有提前预设vuex 模块,

使用commit 出发 muations 的方法,

this.$store.commit(“方法名”)

使用dispatch触发actions 的方法,

this.$store.dispatch(“方法名”)

辅助函数 mapstate 来获取多个状态使用 需要

Import {mapState} from ‘Vuex’
Computed:mapState({ 
  使用方式1
    Abc:‘state中定义的名字’
  使用方式2
    Abc:state=>state.定义的名字
  使用方式3
    Abc(){
      Return this.$store.state.count
     }
})

直接在div中通过{{Abc}}来获取值

是不是很简单呢

【随笔】

你可能感兴趣的:(Vuex的用法)