vuex

2020-09-15  本文已影响0人  GaoXiaoGao

vuex解决不同组件的数据共享 数据持久化

1.vuex的使用

1.src目录下新建一个vuex的文件夹
2.vuex文件夹里面新建一个stroe.js
3.安装vuex
命令为 cnpm install vuex --save
4.在刚才创建的store.js引入vue,引入vuex并且use vuex

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

//安装
Vue.use(Vuex)

//创建对象
const store = new Vuex.Store({
      state:{},
      mutations:{},
      actions:{},
      getters:{},
      modules:{}
})

//导出store
 export default store

5.state在vuex中用于存储数据
var state={
count:1
}

//mutations里面放的是方法,主要用于改变state中的数据
var mutations={

incCount(){
 state.count++;
   }

}

//vuex实例化
const store = new Vuex.Store(
{
state,
mutations:mutations,
gettters,
actions
})

//暴露出实例
export default store

6.在其他页面如Home.vue中如何使用
首先引入
import store from '../vuex/store.js';
然后注册
跟data()平级中注册
export default {
data() {},
store
}

在其他页面中使用,比如访问count
this.$store.state.count

调用方法,触发方法
this.$store.commit('incCount');

2.vuex中的Getter和Action

Getters类似计算属性,改变state数据的时候会触发getters里面的
方法获取新的值

var getters={
computed:(state) =>{
return state.count*2
}
}

//测试
this.$store.getters.computed

Action
Action 类似于mutation
var actions = {
incMutationsCount(context){
//通过context.commit,可以触发一个mutation,执行mutation中的increment方法可以改变state中的数据
context.commit('increment')
}
}

在外部触发action中的方法
this.$store.dispatch('increment');

通过映射函数来调用action中的方法,
例如在App.vue中使用
1.首先需要引入
import {mapActions} from 'vuex'

2.一般在methods中配置,如下
methods:{
//getCatergory为在action中的方法名称
...mapActions(['getCatergory'])
}
3.在需要使用的地方就可以调用
this.getCatergory()

通过映射使用state
1.引入
import {mapState} from 'vuex'

2.配置
computed:{
...mapState(['address','categorys'])

}
3.使用
const {categorys} = this

上一篇 下一篇

猜你喜欢

热点阅读