使用vuex的实例代码
时间: 2023-07-25 15:15:37 浏览: 48
好的,下面是一个简单的 Vue 使用 Vuex 的实例代码:
```javascript
// store.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++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCount(state) {
return state.count * 2
}
}
})
export default store
```
```javascript
// main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
```
```html
<!-- App.vue -->
<template>
<div>
<h2>Count: {{ count }}</h2>
<h2>Double Count: {{ doubleCount }}</h2>
<button @click="increment">Increment</button>
<button @click="incrementAsync">Increment Async</button>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
},
doubleCount() {
return this.$store.getters.doubleCount
}
},
methods: {
increment() {
this.$store.commit('increment')
},
incrementAsync() {
this.$store.dispatch('incrementAsync')
}
}
}
</script>
```
在上面的代码中,我们首先在 `store.js` 中定义了 Vuex 的状态管理器。其中,我们定义了一个名为 `count` 的状态,以及两个修改状态的方法:`increment` 和 `incrementAsync`。我们还定义了一个名为 `doubleCount` 的 getter 方法,用于计算状态的两倍。
然后,在 `main.js` 中,我们将这个状态管理器传递给 `Vue` 实例,让它可以在组件中使用。
在 `App.vue` 组件中,我们使用 `computed` 属性来计算状态和 getter 的值,并使用 `methods` 属性来调用 `increment` 和 `incrementAsync` 方法。这些方法会分别调用 `commit` 和 `dispatch` 方法来修改状态。
这样,我们就完成了一个简单的 Vue Vuex 实例。当用户点击按钮时,状态会自动更新,并且我们可以使用 getter 来计算状态的值。