利用全局getters解决代码嵌套的问题
问题:代码嵌套太深
<div class="avatar-wrapper">
<img :src="$store.state.user.userInfo.staffPhoto" class="user-avatar">
<span>{{ $store.state.user.userInfo.username }}</span>
<i class="el-icon-caret-bottom" />
</div>
解决:把要用的数据在getters里面解构,再用...mapGetters辅助函数
const getters = {
sidebar: state => state.app.sidebar,
device: state => state.app.device,
token: state => state.user.token,
avatar: state => state.user.avatar,
// avatar(state) {
// return state.user.avatar
// },
name: state => state.user.name,
username: state => state.user.userInfo.username,
staffPhoto: state => state.user.userInfo.staffPhoto,
userId: state => state.user.userInfo.userId
}
export default getters
使用getter解构后:
<div class="avatar-wrapper">
<img :src="$store.getters.staffPhoto" class="user-avatar">
<span>{{ $store.getters.name }}</span>
<i class="el-icon-caret-bottom" />
</div>
在getters解构的基础上再使用辅助函数mapGetters
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'username',
'staffPhoto'
])
},
最终简化代码:直接写属性名
<div class="avatar-wrapper">
<img :src=" staffPhoto " class="user-avatar">
<span> {{ username }} </span>
<i class="el-icon-caret-bottom" />
</div>