js 如何使用vuex
时间: 2024-01-31 22:04:27 浏览: 44
以下是使用Vuex的步骤和示例代码:
1.安装Vuex
```shell
npm install vuex --save
```
2.创建store.js文件
```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)
}
},
getters: {
getCount: state => {
return state.count
}
}
})
export default store
```
3.在main.js中引入store.js
```javascript
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
```
4.在组件中使用Vuex
```javascript
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="incrementAsync">Increment Async</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters([
'getCount'
]),
count () {
return this.getCount
}
},
methods: {
...mapActions([
'incrementAsync'
]),
increment () {
this.$store.commit('increment')
}
}
}
</script>
```
阅读全文