vuex 简单实例
时间: 2023-07-05 13:18:27 浏览: 35
下面是一个简单的 Vuex 实例:
1. 安装 Vuex
```
npm install --save vuex
```
2. 创建一个 Vuex Store
```javascript
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)
}
}
})
export default store
```
在上面的代码中,我们创建了一个 Vuex Store,包含了一个状态 count 和两个方法 increment 和 incrementAsync。其中,increment 方法用于同步地增加 count 的值,incrementAsync 方法用于异步地增加 count 的值。
3. 在 Vue 组件中使用 Vuex
```html
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="incrementAsync">Increment Async</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: mapState([
'count'
]),
methods: mapActions([
'increment',
'incrementAsync'
])
}
</script>
```
在上面的代码中,我们使用了 mapState 和 mapActions 辅助函数来将 Vuex 的状态和方法映射到 Vue 组件中。这样,我们就可以在组件中直接使用 count 和 increment、incrementAsync 方法,而不需要显式地访问 Vuex Store。
以上就是一个简单的 Vuex 实例,它演示了如何创建一个 Vuex Store,以及如何在 Vue 组件中使用 Vuex。