v-model father and son to realize two-way binding components

Official website address: https://cn.vuejs.org/v2/api/#model

一, API

  model: { prop?: string, event?: string }

Second, the realization

// 父组件
<template>
  <div id="app">
   // 使用 input 组件,使用 v-model
    <sp-input v-model="value"></sp-input>
    <button @click="Console">显示value</button>
  </div>
</template>

<script>
import input from "../src/components/input";
export default {
  name: "App",
  data() {
    return {
      // 定义 input 需要的 value属性
      value: ''
    };
  },
  components: {
    "sp-input": input
  },
  methods: {
    Console() {
      the console.log (this.Value) 
      Alert ( the this .Value); 
    } 
  } 
};
 </ Script> // subassembly 
<Template> 
  <div> // package input tag, v-model binding property computed 
    <input type = "text" v- = model "InputValue" / 
  </ div> 
</ Template> 
<Script> 
Export default { 
  name: "SP-INPUT" ,
   // define the model attribute   model: {
    // property prop i.e. parent element using v-model binding this name is a custom 
    prop: "value" ,
     // event namely sub-components to the event would be triggered by the parent component, the parent component of the v-model can listen to this event,And vlaue attribute assigned to the v-model binding 
    event: "input"


    


  }, 
  The props: { 
    // prop prop defined herein with the same name to be defined in the model 
    value: String 
  }, 
  computed: { 
    // definition of a calculated attribute, to the subassembly using the v-model 
    InputValue: {
       // Calculation properties returns the parent component get passed value, i.e., model, props defined prop 
      get () {
         return  the this .Value; 
      }, 
      SET (value) { 
        // trigger event to the parent component, this event is defined in the event model, when the trigger subassembly v-model binding property of this calculation, the input set method of calculating an attribute, namely the triggering event parent element 
        the this $ EMIT ( "iNPUT." , value); 
      } 
    } 
  } 
};
 </ Script>

Third, pay attention

1. In addition to the use of computed attribute can also be used to trigger an event @input.

2. Key components of the model for the property

 

谦良恭卑,信诚实至;生活不易,共勉同求。

Guess you like

Origin www.cnblogs.com/elsonww/p/11305806.html