问题描述
我正在 Vue 中创建一个简单的开关切换组件,它有一个 v-model 和 @updated.但是当用户切换开关时,我似乎无法更改模型.首先,我收到错误以避免直接改变道具.但现在我又遇到了另一个错误.
I am creating a simple switch toggle component in Vue where it has a v-model and @updated. But I can't seem to change the model when the user toggles the switch. First I was getting the error to avoid mutating a prop directly. But now I am getting another error.
[Vue 警告]:计算属性isSwitchOn"已分配给但它有没有二传手.
组件应该这样使用
<iswitch v-model="switchGender" @updated="handleUpdatedGender" />
这是组件本身
export default {
template: `
<span
@click="toggleSwitch"
:class="{ active: isSwitchOn }">
<span class="toggle-knob"></span>
</span>
`,
props: ['value'],
methods:
{
toggleSwitch()
{
this.isSwitchOn = !this.isSwitchOn
this.$emit('input', this.isSwitchOn)
this.$emit('updated')
}
},
computed:
{
isSwitchOn()
{
return this.value
}
},
};
推荐答案
错误是由这个语句触发的:this.isSwitchOn = !this.isSwitchOn
.您正在尝试为计算属性赋值,但您没有提供 setter
.
The error is triggered by this statement: this.isSwitchOn = !this.isSwitchOn
. You are trying to assign a value to a computed property but you didn't provide a setter
.
您需要如下定义您的计算属性,使其作为 getter
和 setter
工作:
You need to define your computed property as follow for it to work as a getter
and a setter
:
computed:
{
isSwitchOn:
{
get()
{
return this.value
},
set(value)
{
this.value = value
}
}
}
另外,不建议直接修改 prop.您可以做的是添加一个新的数据属性并使用观察者将其与 value
道具同步.
Also, it is not advised to mutate a prop directly. What you could do is to add a new data property and sync it with the value
prop using a watcher.
我认为这样的事情会奏效:
I think something like this will work:
props: ['value'],
data()
{
return {
val: null
}
},
computed:
{
isSwitchOn:
{
get()
{
return this.val
},
set(value)
{
this.val = value
}
}
},
watch: {
value(newVal) {
this.val = newVal
}
}
这篇关于计算属性已分配给但没有设置器 - 切换组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!