如何从 mapState() 内部访问组件数据?
How to access component data from inside mapState()?
根据我的道具 buttonType
的值,我想检索不同的存储变量:
...mapState({
backgroundColor: state => this.buttonType === 'primary'
? state.primary_button.background_color
: state.secondary_button.background_color
})
虽然这不起作用,因为箭头函数有它们自己的 this
。所以我尝试了:
...mapState({
backgroundColor: function(state) {
return this.buttonType === 'primary'
? state.primary_button.background_color
: state.secondary_button.background_color
}
})
出现此错误:
Expected method shorthand
正确的做法是什么?
我会把它分成三个道具:primaryColor
和 secondaryColor
(使用 mapState
),然后是一个单独的计算道具,returns 其中一个基于buttonType
:
export default {
computed: {
...mapState({
primaryColor: state => state.primary_button.background_color,
secondaryColor: state => state.secondary_button.background_color,
}),
backgroundColor() {
return this.buttonType === 'primary'
? this.primaryColor
: this.secondaryColor
}
}
}
或者如果你只想要一个道具,你可以直接参考商店的状态:
export default {
computed: {
backgroundColor() {
return this.buttonType === 'primary'
? this.$store.state.primary_button.background_color
: this.$store.state.secondary_button.background_color
}
}
}
根据我的道具 buttonType
的值,我想检索不同的存储变量:
...mapState({
backgroundColor: state => this.buttonType === 'primary'
? state.primary_button.background_color
: state.secondary_button.background_color
})
虽然这不起作用,因为箭头函数有它们自己的 this
。所以我尝试了:
...mapState({
backgroundColor: function(state) {
return this.buttonType === 'primary'
? state.primary_button.background_color
: state.secondary_button.background_color
}
})
出现此错误:
Expected method shorthand
正确的做法是什么?
我会把它分成三个道具:primaryColor
和 secondaryColor
(使用 mapState
),然后是一个单独的计算道具,returns 其中一个基于buttonType
:
export default {
computed: {
...mapState({
primaryColor: state => state.primary_button.background_color,
secondaryColor: state => state.secondary_button.background_color,
}),
backgroundColor() {
return this.buttonType === 'primary'
? this.primaryColor
: this.secondaryColor
}
}
}
或者如果你只想要一个道具,你可以直接参考商店的状态:
export default {
computed: {
backgroundColor() {
return this.buttonType === 'primary'
? this.$store.state.primary_button.background_color
: this.$store.state.secondary_button.background_color
}
}
}