vuex 状态管理
定义:专为VUe.js应用程序开发的状态管理模式。
-
安装
npm install vuex --save
-
使用创建store目录index文件中
import Vue from "vue"
import Vuex from "vuex"
VUe.use(Vuex)//使用插件
export default new Vuex.store({
})
-
在main.js中引入
import store from"./store" new VUe({ store })//注册后可以在this中调用$store
-
实例里面的属性
-
state:{
count:1
}
相当于data属性数据共享可以用this.$store.state拿到
-
mutations:{//修改的方法写在其中,在其他页面调用,要用this.$store.commit(‘addCount’,10)
addCount(state,num){
//mutations中定义的方法,都有两个参数
//第一个参数默认为state
//第二个参数为传进来的参数,可以传一个对象
state.count+=num
}
}
-
action:{
//其他可以包含任意异步操作
//action是提交mutation,不能直接变更状态
addAsync(store){
store.commit(‘addCount’,200)
}
}
-
getters相当于计算属性,会被缓存;
-
module 模块化
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ strict: true, // 在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误 state: { // 状态,数据 count: 1, cart: [] }, getters: { // 根据 state 派生的新的状态,相当于 computed // 这些派生的新数据会被缓存,当依赖发生改变时,再重新计算 totalCount(state) { return state.count * 5 }, avgCount(state) { return state.count / 3 } }, mutations: { // 通常是同步修改 state 的方法 // mutations 中定义的方法,都有两个参数 // 第一个参数固定为 state // 第二个参数为方法所需要额外的一些数据 addCount(state, payload) { // console.log(arguments) // state.count = (state.count + payload.num1) * payload.num2 state.count += payload } }, actions: { // 异步修改state // 参数传递的是 store对象 addCountAsync(store) { setTimeout(() => { // 错误:不能直接变更状态 // store.state.count += 100 // 正确:提交 mutation store.commit("addCount", 200) }, 2000) } } })
结构方式调用
<script> import { mapState, mapMutations, mapActions, mapGetters } from "vuex" export default { name: "Cart", computed: { ...mapState(['count']), ...mapGetters(['totalCount', 'avgCount']), myCount() { return this.$store.state.count } }, created() { console.log(this) }, methods: { ...mapMutations(['addCount']), ...mapActions(['addCountAsync']), /*addCount() { // this.$store.state.count += 1 // 通过 store 的 commit 方法,来调用到 store 中定义在 mutations 里的方法 this.$store.commit('addCount', {num1: 10, num2: 2}) }*/ } } </script>
插件
[在 Scrimba 上尝试这节课Vuex 的 store 接受
plugins
选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 作为唯一参数:const myPlugin = store => { // 当 store 初始化后调用 store.subscribe((mutation, state) => { // 每次 mutation 之后调用 // mutation 的格式为 { type, payload } }) }
然后像这样使用:
const store = new Vuex.Store({ // ... plugins: [myPlugin] })
-