写一个uniapp使用vuex的模板
时间: 2023-12-09 08:55:50 浏览: 40
好的,以下是一个Uniapp使用Vuex的模板:
1. 在根目录下创建一个store目录,里面包含一个index.js文件和一个modules目录。
2. 在index.js文件中引入Vue和Vuex,创建一个Vuex实例并导出。
3. 在modules目录中创建一个模块,例如app.js,在其中定义state、mutations、actions和getters。
4. 在index.js文件中导入该模块,并使用Vue.use(Vuex)注册Vuex插件。
5. 在App.vue中引入store,并在Vuex.Store选项中传入该store实例。
index.js文件示例:
```
import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app
}
})
export default store
```
app.js文件示例:
```
const state = {
count: 0
}
const mutations = {
increment(state) {
state.count++
}
}
const actions = {
increment({ commit }) {
commit('increment')
}
}
const getters = {
getCount: state => state.count
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
```
App.vue文件示例:
```
<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters('app', ['getCount']),
count () {
return this.getCount
}
},
methods: {
...mapActions('app', ['increment'])
}
}
</script>
<style>
</style>
```