vue.js - Vue js如何使用props值到v-model
问题描述
我有两个组件,即App.vue和hello.vue
在App组件中,我导入hello组件并使用 props 将相关数据传递给hello组件。在那里我绑定了从App组件中获取的数据。
在我的 hello 组件中,我input box
绑定了传递的值。
我的最终目标是将值作为道具传递给hello组件并对其进行更改,最后使用 save 方法将编辑后的值传递给后端。
我如何做到这一点?
这是我到目前为止所做的。
应用程序.vue
<template>
<div id="app">
<hello-world :msg="'hello good morning'"></hello-world>
</div>
</template>
<script>
import helloWorld from "./components/HelloWorld";
export default {
components: {
helloWorld
}
};
</script>
你好.vue
<template>
<div>
<input type="text" :value="msg">
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
}
};
</script>
在我的 hello 组件的输入字段中,v-model 是不可能的。我想要类似于 v-model 的东西。
解决方案
You cannot use prop
to bind to v-model
. Child component is not supposed to modify prop
passed by the parent component.
You will have to create a copy of prop
in your child component if you wish to use prop
with v-model
and then watch prop
like this:
<template>
<div>
<input type="text" @input="onInput" v-model="msgCopy">
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
},
data() {
return { msgCopy: '' };
},
methods: {
onInput(newInputValue) {
this.$emit('msgChange', newInputValue);
}
}
watch: {
msg(newVal) {
this.msgCopy = newVal;
}
}
};
</script>
Also, notice the use of event handler @input
to pass changed prop
back to the parent component via event. As a syntax sugar, you can make your Hello
component work as a custom form input control by adopting to v-model
lifecycle.
推荐阅读
- c++ - delete[something] 在 Visual Studio 中有什么作用?
- sql - 强制 5 分钟间隔到日期时间 SQL Server 2012
- swift - Swift 从服务器到使用
- c++ - 减少用函数值定义的变量的值
- wordpress - WORDPRESS 用户通过 ID 访问特定联系表格 CFDB7
- amazon-s3 - 汇合平台 S3SinkConnector 不工作
- javascript - 是否可以将数据附加到 Firebase Analytics page_view 事件?
- python - 如何将项目附加到类对象的属性?
- xcode - 在 XCTest UI 测试中单击 NSToolbarItem
- r - 结合两个数据框,相似的行,相似的列,除了一个列具有不同的值