[英]How to Emit values from child to an object in parent component in vuejs?
我正在嘗試使用帶有自定義表單輸入的子組件並將這些值發送到父組件。 但是,當我嘗試將值存儲在父組件的 object 中時,當輸入另一個輸入值時,一個輸入值會消失。 讓我展示一些代碼:
<template>
<input
type="text"
@input="setField($event.target.value, 'title')"
/>
<wysiwyg-input
@change="(text) => setField(text, 'content')"
/>
</template>
<script>
export default {
methods: {
setField(value, field) {
this.$emit("input", {
title: field === "title" && value,
content: field === "content" && value,
});
},
},
}
</script>
<template>
<FormFields v-model="blogPost" />
</template>
<script>
export default {
data() {
return {
blogPost: {},
};
},
watch: {
blogPost(val) {
console.log(val);
},
},
};
</script>
在這里,當我嘗試輸入“內容”時,“標題”字段變為假。 那么如何在子組件上設置條件,因為我可以將兩個輸入都發送到父組件? 或任何其他想法來完成相同的任務?
CodeSandbox 鏈接: https://codesandbox.io/s/mystifying-benz-w8wgu?file=/src/App.vue
您可以使用三元運算符:
this.$emit("input", {
title: field === "title" ? value : "",
content: field === "content" ? value : "",
});
根據MDN 文檔
&&
運算符實際上返回指定操作數之一的值
expr1 && expr2
If expr1 can be converted to true, returns expr2; else, returns expr1
const a = 3; const b = -2; console.log(a > 0 && b > 0); // which returns false as expression `a > 0` true and b > 0 is `false` returned.
在你的情況下
如果 filed = 'title', field === "title" && value
將返回value
如果 filed = 'somethingelse', field === "title" && value
將返回false
。
正如 Serg 提到的,您可以使用三元運算符來解決您的問題。
this.$emit("input", {
title: field === "title" ? value : "",
content: field === "content" ? value : "",
});
真棒問題
為什么我們不在子組件中使用 this.value? 在您的代碼中,父組件將 v-model="blogPost" 傳遞給子組件,但在未使用的子組件中。
嘗試這個
在子組件中:
<template> <input type="text" @input="setField($event.target.value, 'title')" /> <wysiwyg-input @change="(text) => setField(text, 'content')" /> </template> <script> export default { props: { value: { type: Oject } }, methods: { setField(value, field) { this.$emit("input", { title: field === "title"? value: this.value.title, content: field === "content"? value: this.value.content, }); }, }, } </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.