自定义组件v-model

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框等类型的输入控件可能会将 value attribute 用于不同的目的model 选项可以用来避免这样的冲突。(文档介绍)

v-model实现表单输入的双向绑定

<input v-model="price">

实现理解

 <input type="text" :value="inner" @input="inner=$event.target.value">

将输入框内容绑定到inner变量,当input框内容发生变化时触发input事件,将input内容赋值给inner。

自定义组件使用v-model指令原理相通

  1. 我们的子组件的value需要绑定一个从父组件传来的值,通过子组件的props接收
  2. 在子组件上value变化将value映射给父组件
<template>
  <div id="app">
    <child v-model="name"></child>
    <button type="button" @click="changeProvide">change</button>
  </div>
</template>

<script>
import Child from "@/components/Child";
export default {
  name: "App",
  data() {
    return {
      name: 0
    }
  },
  components: {
    Child,
  },
  methods: {
    changeProvide() {
      console.log(this.name)
    }
  }
};
</script>

  

<template>
  <div class="child">
    <button @click="changeValue">child</button>
  </div>
</template>

<script>
import ChildDeep from '@/components/ChildDeep'
export default {
  name: "Child",
  props: {
    value: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      sum: 0
    }
  },
  methods: {
    changeValue() {
      this.$emit('input', this.sum++);
    }
  }
}
</script>

  

posted @ 2020-12-10 17:45  eightabs  阅读(353)  评论(0编辑  收藏  举报