Vueカスタムv-model

13757 ワード

Vueの双方向データバインディングは、親コンポーネントが子コンポーネントの同じデータを変更し、子コンポーネントのデータが親コンポーネントの同じデータを変更できることです.
カスタムv-model
親コンポーネント:
<template>
  <div class="home">
    {{ value }}
    <Search v-model="value">Search>
  div>
template>
<script>
import Search from '@/components/Search'
export default {
  data() {
    return {
      value: "123"
    }
  },
  components: {
    Search
  }
}
script>

サブアセンブリ:最初の方法
<template>
  <div class="seach">
    <input v-model="val" />
  div>
template>
<script>
export default {
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  data () {
    return {
      val: ""
    }
  },
  methods: {
    handle() {
      this.val != this.val;
    }
  },
  watch: {
    value: {
      handler () {
        this.val = this.value;
      },
      immediate: true
    },

    val () {
      this.$emit("change", this.val);
    }
  }
}
script>

サブアセンブリ:第2の方法
<template>
  <div class="seach">
    <input v-model="val" @input="onInput" />
  div>
template>
<script>
export default {
  model: {
    prop: "value",
    event: "input" //      change
  },
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  data () {
    return {
      val: ""
    }
  },
  methods: {
    onInput(e) {
      this.val = e.target.value;
      //      change     model    event      
      this.$emit("input", this.val);
    }
  },
  watch: {
    value: {
      handler () {
        this.val = this.value;
      },
      immediate: true
    }
  }
}
script>

上の2つのコンポーネントは、サブコンポーネントSearchコンポーネントのカスタムv-modelを実現しています.