一、uniapp中有自带vuex插件,直接引用即可
二、在项目中新建文件夹store,在main.js中导入
- 在根目录下新建文件夹store,在此目录下新建index.js文件
- index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 方法1(直接写)
const store = new Vuex.Store({
state: {
//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
text1: 1
},
getters: {
// state的计算属性
get1: state => {
return state.text1 + 1
},
get2: (state, getters) => {
//state :可以访问数据
//getters:访问其他函数,等同于 store.getters
return getters.get1
},
getTodoById: (state) => (value) => {
return state.text1 + value
}
},
mutations: {
//相当于同步的操作
//传递数值
add(state, n) {
state.text1 += n
}
//传递对象类型
add(state, payload) {
state.text1 += payload.value
}
},
actions: {
//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
addCountAction (context , payload) {
context.commit('add',payload)
}
}
})
export default store
// 方法二(分模块)
// 如果将store分成一个个的模块的话,则需要用到modules。
//然后在每一个module中写state, getters, mutations, actions等。
import cart from '@/store/modules/cart.js'
export default new Vuex.Store({
modules:{
cart
}
})
- 在main.js中导入挂载vuex
三、使用
- 第一种方式:this.$store直接操作
例如当取值:直接在页面中使用this.$store.state.变量名
- 第二种方法:mapState, mapGetters, mapActions, mapMutations
<template>
<view class="content">
</view>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
import store from '@/store/index.js';
//导入
export default {
data() {
return {
}
},
computed: {
//computed中注册
...mapGetters(['get1']),
// 不用modules对应写法
...mapState([
'text1'
])
// 用modules对应写法
...mapState({
text1:state=>state.cart.text1
})
}
methods: {
...mapMutations(['add']),
...mapActions(['addCountAction'])
// 下面示例调用各种方法,就直接用store了
// getters
this.$store.getters.get1
// mutations
store.commit('add')
// actions 以对象形式分发
store.dispatch({
type: 'addCountAction',
amount: 5
})
}
}
</script>
<style>
</style>