美文网首页
vue 自定义组件使用v-model

vue 自定义组件使用v-model

作者: 彬彬彬boboc | 来源:发表于2021-05-26 16:40 被阅读0次

app.vue

<div id="app">
  <my-component v-model="msg"></my-component>
  msg: {{msg}}
  <my-counter v-model="num"></my-counter>
  num: {{num}}
</div>

my-component.vue

<template>
  <div>
    <input type="text" :value="currentValue" @input="handleInput"/>
  </div>
</template>
<script>
export default {
  data() {}
  computed:{
    currentValue () {
      return this.value
    }
  },
  props: ['value'], //接收一个 value prop
  methods: {
    handleInput(event) {
      var value = event.target.value;
      this.$emit('input', value); //触发 input 事件,并传入新值
    }
  }
});
</script>

相关文章

网友评论

      本文标题:vue 自定义组件使用v-model

      本文链接:https://www.haomeiwen.com/subject/npgksltx.html