vue 取@/store的方法
时间: 2023-12-04 10:05:29 浏览: 24
要在Vue组件中使用`@/store`中的方法,你需要先引入`mapMutations`方法。然后,你可以使用`mapMutations`方法将`common`模块中的`setState`方法映射到组件的`methods`中。这样,你就可以在组件中调用`this.getSetState`方法来改变`common`模块中的状态。例如,在点击按钮时,你可以调用`this.getSetState({ name: 'clientId', val: 123 })`来改变`common`模块中`clientId`的值为123。然后,你可以通过`this.$store.state.common.clientId`来获取更新后的值。
相关问题
vue3中在setup中取store里面getters里面的方法如何取
你可以通过使用Vuex的useStore方法来获取store对象,然后从中选取所需的getters方法。例如,可以这样写:
```
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const myGetter = store.getters['myModule/myGetter'];
// do something with myGetter
return {
// return some values
}
}
}
```
这样,你就可以在Vue 3中的setup函数中访问你需要的store getters了。
vue2 vuex 存和取
在Vue2中,使用Vuex进行数据的存储和获取非常方便。下面是一个简单的示例来演示如何在Vue2中使用Vuex进行数据的存储和获取[^1]:
1. 首先,安装Vuex和vuex-persist插件:
```shell
npm install vuex --save
npm install vuex-persist --save
```
2. 在Vue项目的入口文件(通常是main.js)中引入Vuex和vuex-persist插件,并创建一个Vuex的store实例:
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'
Vue.use(Vuex)
const vuexPersist = new VuexPersist({
key: 'my-app',
storage: window.localStorage
})
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
}
},
plugins: [vuexPersist.plugin]
})
new Vue({
store,
// ...
}).$mount('#app')
```
3. 在组件中使用store中的数据和方法:
```vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
increment() {
this.$store.dispatch('increment')
}
}
}
</script>
```
通过上述步骤,你可以在Vue组件中使用`$store.state`来获取存储在Vuex中的数据,使用`$store.commit`来修改数据,使用`$store.dispatch`来触发异步操作。