我正在尝试制作可重用的自定义Switch组件,但是我的v模型无法正常工作。情况如下:
以下是一些片段,显示了我的设置:
// MY COMPONENT
<template>
<Switch
dock="right"
backgroundColor="red"
offBackgroundColor="yellow"
v-model="model"
/>
</template>
<script>
export default {
name: "SettingsSwitch",
props: {
value: {
type: Boolean,
required: true
}
},
data() {
return {
model: this.value
};
},
watch: {
model: function(value) {
this.$emit("tap", value);
}
}
};
</script>
在下面的示例中,我有2个开关: -正常工作并且其数据已更新 -链接到我的子组件且数据未更新的那个
// My parent view
<template>
<ViewWrapper viewTitle="Change your settings" pageColor="tertiary">
<StackLayout class="content-wrapper">
<StackLayout class="category-wrapper">
<DockLayout class="field-wrapper" stretchLastChild="true">
<Switch v-model="myCheck" dock="right" @tap="test" />
<StackLayout>
<Label text="Mon label" class="field-label" />
<Label text="Ma valeur actuelle" class="field-value" />
</StackLayout>
</DockLayout>
<DockLayout class="field-wrapper" stretchLastChild="true">
<SettingsSwitch v-model="myCheck2" @tap="test2" />
<StackLayout>
<Label text="Mon label" class="field-label" />
<Label text="Ma valeur actuelle" class="field-value" />
</StackLayout>
</DockLayout>
</StackLayout>
</StackLayout>
</ViewWrapper>
</template>
<script>
import { ViewWrapper } from "@/components";
import SettingsSwitch from "./SettingsSwitch";
export default {
name: "Settings",
components: { ViewWrapper, SettingsSwitch },
data() {
return {
myCheck: false,
myCheck2: false
};
},
methods: {
test() {
console.log(this.myCheck);
},
test2(v) {
console.log("emit", v); // <--- Value changes each time
console.log("model", this.myCheck2); // <--- Value never changes
}
}
};
</script>
我尝试使用不同的设置,例如删除watch
并直接调用执行$emit
的方法,但这似乎无法解决问题
有什么想法吗?
答案 0 :(得分:0)
所以我设法解决了这个问题。我的错误是我在组件中发出tap
而不是input
。我感到很愚蠢,但我放弃了这个,反而有人像我一样挣扎了
底线是:
您可以在任何标签上使用v-model ,但是为了更新其值,它将需要接收带有一些数据的“输入”事件。这就是为什么我的子组件必须执行this.$emit("input", value);