1、页面中使用
创建store
在src目录下创建一个store文件夹,里面创建一个index.js文件,用于创建和管理vuex的store。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
//定义初始状态
count: 0
},
mutations: {
//定义修改状态的方法
increment(state) {
state.count++
}
}
})
export default store
组件中使用
在组件中引入store,并使用mapState、mapGetters、mapMutations等函数进行操作。
import { mapState, mapMutations } from 'vuex'
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapMutations(['increment'])
}
}
在模板中使用
<template>
<view>
<text>count: {{count}}</text>
<button @tap="increment">click me</button>
</view>
</template>
在上述例子中,通过mapState将store中的count状态映射到组件的计算属性count中;通过mapMutations将store中的increment方法映射到组件的methods中。在模板中就可以方便地使用这个状态和方法了。
2、全局注册
使用vuex 需要在main.js中引入并添加到Vue的prototype原型中
import store from "./store/store.js"
Vue.prototype.$store = store
getters在界面中的使用 将会获取到vuex中state中的box属性
this.$store.getSelect();
mutations的使用
this.$store.commit("setSelect",“新的数据”)
mutations的使用需要调用 commit方法 该方法接收两个参数 第一个是字符串 对应mutations中的方法名 表示调用mutations中的方法 第二个参数可以是任意的数据类型 第二个值将会作为参数传递进对应的调用方法;在对应的方法中获取到传递的数据后即可对state中的数据进行修改
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: { box:"数据",
},
getters:{
getSelect(state){
return state.box
}
},
mutations: {
setSelect(state,item){
state.box = item
},
}
})
export default store