首页 文章

Vue js如何将道具值用于v-model

提问于
浏览
0

我有两个组成部分 App.vuehello.vue

App 组件中,我导入 hello 组件并使用props将相关数据传递给 hello 组件 . 在那里我绑定从 App 组件获取的数据 .

在我的hello组件中,我对传递的值有一个 input box 绑定 .

我的最终目标是将值作为道具传递给 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模型的东西 .

1 回答

  • 0

    您不能使用 prop 绑定到 v-model . 子组件不应该修改父组件传递的 prop .

    如果您希望将 propv-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 组件作为自定义表单输入控件工作 .

相关问题