Vue3从入门到实战 vuex基本使用
时间: 2023-09-14 18:14:17 浏览: 76
Vue3是目前最新的Vue.js版本,相比Vue2有很多新特性和更好的性能。而Vuex是Vue.js官方推荐的状态管理工具,用于处理复杂的应用程序中的共享状态。
下面是Vue3和Vuex的基本使用方法:
1. 在项目中安装Vue3和Vuex:
```bash
npm install vue@next vuex@next --save
```
2. 创建一个store.js文件用于配置Vuex:
```javascript
import { createStore } from 'vuex'
const store = createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
}
},
getters: {
getCount(state) {
return state.count
}
}
})
export default store
```
这里我们定义了一个state对象来存储应用程序的状态,一个mutation函数来改变状态,一个action函数来分发mutation,一个getter函数来获取状态。
3. 在main.js中引入store:
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
```
4. 在组件中使用Vuex:
```html
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters(['getCount']),
count() {
return this.getCount
}
},
methods: {
...mapActions(['increment'])
}
}
</script>
```
这里我们使用了Vuex提供的mapGetters和mapActions函数来映射state中的count属性和increment函数到组件中。
以上就是Vue3和Vuex的基本使用方法,可以根据自己的需求进行扩展和修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)