我有两个组件,即 App.vue 和 hello.vue
在 App 组件中,我导入 hello 组件,并使用 props 将相关数据传递给 hello 组件。 我在那里绑定(bind)从 App 组件获取的数据。
在我的 hello 组件中,我有一个输入框
绑定(bind)到传递的值。
我的最终目标是将值作为 Prop 传递给 hello 组件并更改它,最后 使用 save 方法将编辑后的值传递到后端。
如何实现这一目标?
这就是我到目前为止所做的。
App.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>
hello.vue
<template>
<div>
<input type="text" :value="msg">
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
}
};
</script>
在我的 hello 组件的输入字段中 v-model 是不可能的。我想要类似于 v 模型的东西。
最佳答案
您不能使用 prop
绑定(bind)到 v-model
。子组件不应修改父组件传递的 prop
。
如果您希望将 prop
与 v-model
一起使用,则必须在子组件中创建 prop
的副本,然后观看prop
像这样:
<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>
此外,请注意事件处理程序 @input
的使用,通过事件将更改的 prop
传递回父组件。作为语法糖,您可以通过采用 v-model
生命周期使您的 Hello
组件用作自定义表单输入控件。
关于vue.js - Vue js如何使用props值到v-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52383065/