如何在Vue中自己实现v-model

时间:2022-07-26
本文章向大家介绍如何在Vue中自己实现v-model,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

MyInput.vue

<template>
    <div>
        <input type="text" :value="text" @input="$emit('change',$event.target.value)"> 
    </div>
</template>
<script>
export default {
    model:{
        prop:'text',  // 对应到props text
        event:'change'
    },
    props:{
        text:String
    }
}
</script>

调用

<template>
  <div>  {{text}}
    <MyInput v-model="text"></MyInput>
  </div>
</template>
<script>
import MyInput from '../components/MyInput'
export default {
  components:{
      MyInput
  },

  data(){
    return {
      text:''
    }
  }
}
</script>