根据属性更新默认状态



我正在处理一个按钮组件,该组件也接收默认状态值。

export default {
props: {
defaultState: {
type: Boolean,
default: false
}
},
data() {
return {
currentState: this.defaultState
}
},
computed: {
isActive() {
return this.currentState;
},
}
...
}

我可以像<button :defaultState="true"/>一样使用它.

现在的问题是,当我尝试为我的组件编写测试时,在使用应该为truewrapper.setProps({ defaultState: true })后,我总是得到false(这是默认值)值currentState

it.only ('should work with dynamic state change', async () => {
wrapper.setProps({
defaultState: true
});
await wrapper.vm.$nextTick();
// shows the true
console.log( wrapper.vm.defaultState );
// should be true but i get false 
console.log( wrapper.vm.currentState );
});

谁能指出我正确的方向和我错过了什么?

更好的解决方案是创建一个计算属性。这将消除对数据属性和观察程序的需求:

export default {
props: { 
defaultState: {
type: Boolean,
default: false
}
},
computed: {
currentState() {
return this.defaultState
}
}
}

但是,如果您的组件如此简单,则根本不需要计算的currentValue属性!因为它所做的一切都重复了defaultState道具的值,而道具本身已经是反应性的。

因此,这意味着您正在增加组件的复杂性,只是为了让它适用于测试......即使您没有这个组件,该组件也会完美运行。

最新更新