在uni-app 下引入状态
时间: 2023-12-06 11:04:37 浏览: 37
在uni-app中,可以通过Vuex来引入状态。
1. 在src目录下新建一个store文件夹,并在store文件夹中新建一个index.js文件,代码如下:
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count--
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
getCount: state => {
return state.count
}
}
})
export default store
```
2. 在main.js中引入store并挂载到Vue实例上,代码如下:
```
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()
```
3. 在需要使用状态的组件中,使用mapState、mapMutations、mapActions、mapGetters等函数来获取状态,代码如下:
```
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
<button @click="incrementAsync">Increment Async</button>
<p>GetCount: {{ getCount }}</p>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
computed: {
...mapState({
count: state => state.count
}),
...mapGetters([
'getCount'
])
},
methods: {
...mapMutations([
'increment',
'decrement'
]),
...mapActions([
'incrementAsync'
])
}
}
</script>
```
以上代码中,mapState函数将state中的count映射到组件的计算属性中,mapMutations函数将mutations中的increment和decrement映射到组件的方法中,mapActions函数将actions中的incrementAsync映射到组件的方法中,mapGetters函数将getters中的getCount映射到组件的计算属性中。
通过以上步骤,即可在uni-app中引入状态。