【问题标题】:How to pass the v-model data to the custom component?如何将 v-model 数据传递给自定义组件?
【发布时间】:2021-08-25 18:35:51
【问题描述】:

我在 Vue 中创建了一个自定义输入组件

<template>
  <input :type="inputType" :placeholder="placeholder" v-model="vModel"  />
</template>

<script>
export default {
  name: "BaseInput",
  props: {
    inputType: String,
    placeholder: String,
    label: String,
    vModel: String,
  },
};
</script>

我不知道如何准确传递要从我们调用自定义组件的地方限定的数据

我的应用程序.vue

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <base-input inputType="text" placeholder="Enter Name" vModel="inputName">
  </base-input>
</template>

<script>
import BaseInput from "./components/BaseInput.vue";

export default {
  name: "App",
  components: {
    BaseInput,
  },
  data() {
    return {
      inputName: "",
    };
  },
};
</script>

我提到了How to enable v-model on custom component?,但我听不懂

我怎样才能做到这一点?提前致谢

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    baseInput 应该将modelValue 定义为prop,它将绑定到输入值,使用this.$emit("update:modelValue",e.target.value) 发出新的类型值并将update:modelValue 添加到emits 选项:

    <template>
      <input :type="inputType" :placeholder="placeholder" :value="modelValue" @input="onInput" />
    </template>
    
    <script>
    export default {
      name: "BaseInput",
      props: {
        inputType: String,
        placeholder: String,
        label: String,
        modelValue: String,
      }, 
     emits:["update:modelValue"],
      methods:{
        onInput(e){
          this.$emit("update:modelValue",e.target.value)
        }
      }
    };
    </script>
    

    在父组件中使用它:

    <base-input inputType="text" placeholder="Enter Name" v-model="inputName">
    

    如果您想使用脚本设置,请查看this answer

    【讨论】:

    • 非常感谢。但是你能解释一下吗?我的意思是我们没有任何作为 modelValue 的道具,但是我们如何获得它的价值?
    • 不客气,v-model 指令等同于发出的事件update:modelValue 和道具model 请检查此v3.vuejs.org/guide/…
    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 2021-09-12
    • 2023-01-16
    • 2017-11-07
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多