vue2计算属性中的...mapState("user", ["userInfo"]), ...mapGetters(["sidebar", "avatar", "username", "staffPhoto"]改为vue3写法
时间: 2024-02-15 16:00:48 浏览: 70
解决VUEX的mapState/...mapState等取值问题
5星 · 资源好评率100%
在Vue 3中,计算属性的写法有所改变。下面是将Vue 2中的`...mapState("user", ["userInfo"])`和`...mapGetters(["sidebar", "avatar", "username", "staffPhoto"])`转换为Vue 3写法的示例:
1. `...mapState("user", ["userInfo"])`的Vue 3写法:
```javascript
import { computed, useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const userInfo = computed(() => store.state.user.userInfo);
return {
userInfo
};
}
}
```
2. `...mapGetters(["sidebar", "avatar", "username", "staffPhoto"])`的Vue 3写法:
```javascript
import { computed, useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const sidebar = computed(() => store.getters.sidebar);
const avatar = computed(() => store.getters.avatar);
const username = computed(() => store.getters.username);
const staffPhoto = computed(() => store.getters.staffPhoto);
return {
sidebar,
avatar,
username,
staffPhoto
};
}
}
```
需要注意的是,在Vue 3中,我们使用`computed`函数来创建计算属性,并且使用`useStore`函数来获取Vuex的store实例。然后,我们可以通过调用`store.state`来访问状态,通过调用`store.getters`来访问getters。最后,将计算属性返回给组件的setup函数即可。
阅读全文