How to use Vuex in UniApp
Introduction
Vuex is a state management tool that allows you to centrally manage applications in Vue.js applications Program state and logic. As a cross-platform development framework, UniApp also supports the use of Vuex.
Install Vuex
First, use the following command to install Vuex dependencies:
<code class="bash">npm install vuex --save</code>
or
<code class="bash">yarn add vuex</code>
Create Vuex storage
Next, create a Vuex store that will contain the application's state and logic.
<code class="javascript">// store/index.js import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount (state) { return state.count } } }) export default store</code>
Using Vuex in a component
To access the Vuex store from a component, you can use this.$store
.
<code class="javascript">// App.vue <template> <div>{{ this.$store.state.count }}</div> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </template> <script> import { mapActions } from 'vuex' export default { methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script></code>
Modular Vuex Store
For large applications, it is useful to split the Vuex store into multiple modules. Each module can manage its own state and logic.
<code class="javascript">// store/index.js import Vuex from 'vuex' import Vue from 'vue' import counter from './modules/counter' Vue.use(Vuex) const store = new Vuex.Store({ modules: { counter } }) export default store</code>
<code class="javascript">// store/modules/counter.js export default { state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount (state) { return state.count } } }</code>
Tip
this.$store
. mapActions
and mapState
. The above is the detailed content of How to use vuex in uniapp. For more information, please follow other related articles on the PHP Chinese website!