vue2 vuex 存取数据
时间: 2023-07-14 21:58:41 浏览: 57
在Vue.js 2中使用Vuex存取数据,首先你需要安装并引入Vuex库。然后,你需要在你的Vue应用中创建一个store实例,该实例将包含你的应用所有的共享数据。
首先,在你的项目中安装Vuex:
```
npm install vuex
```
然后,在你的入口文件(比如main.js)中引入Vuex并创建一个store实例:
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// 在这里定义你的共享数据
count: 0
},
mutations: {
// 在这里定义修改state的方法
increment(state) {
state.count++
}
},
actions: {
// 在这里定义触发mutations的方法
increment(context) {
context.commit('increment')
}
},
getters: {
// 在这里定义获取state的方法
getCount: state => state.count
}
})
new Vue({
store,
// ...其他配置
}).$mount('#app')
```
现在,你可以在你的Vue组件中通过以下方式来存取数据:
1. 使用`this.$store.state`来获取state中的数据:
```javascript
this.$store.state.count
```
2. 使用`this.$store.commit`来触发mutations中的方法,修改state的数据:
```javascript
this.$store.commit('increment')
```
3. 使用`this.$store.dispatch`来触发actions中的方法,间接地修改state的数据:
```javascript
this.$store.dispatch('increment')
```
4. 使用`this.$store.getters`来获取getters中的数据:
```javascript
this.$store.getters.getCount
```
这样,你就可以在Vue组件中存取Vuex中的数据了。记得在组件中使用`computed`来实时获取数据的变化。