首页 > 解决方案 > Vue js如何使用props值到v-model

问题描述

我有两个组件,即App.vuehello.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 的东西。

标签: vue.jsvuejs2

解决方案


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.


推荐阅读