【发布时间】:2020-08-07 07:15:13
【问题描述】:
我正在尝试制作一个可重复使用的自定义 Switch 组件,但我的 v-model 无法正常工作。情况如下:
- 我的组件正确地发出了点击事件
- 我的组件正确更新了它的数据
- 但是,尽管使用 v-model 连接到子级,但父级数据不会更新
这里有一些显示我的设置的 sn-ps:
// 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 的方法,但似乎无法解决问题
有什么想法吗?
【问题讨论】:
标签: vue.js nativescript nativescript-vue