The detailed use of V-model in vue3. X

Time:2021-4-18

1. When used to customize components, the prop and default event name of V-model are changed, and the model option is removed

//Parent component

  
    
    Bound value: {message}}
  



//Subcomponents

  
    
  


export default {
  //2. X usage, you can modify the prop and trigger the event name, model to discard
  // model: {
  //Prop: 'value', // the default value of 3. X is changed to modelvalue
  //Event: 'input' // 3. X the default value is changed to update:modelValue
  // },
  props:['modelValue']
}

2. X except model configuration, 3. X how to configure other props?

//Parent component

  
    
    Bound value: {message}}
  


//Subcomponents

  
    
  


export default {
  //3. X receives the value after the V-model colon, and the corresponding trigger method is changed to update:text
  props:['text']
}

2. 3. X new, you can define multiple v-models

//Parent component

  
    
    Bound value 1: {message 1}
    Bound value 2: {message 2}
  


//Subcomponents

  
    
    
  


export default {
  //The value is not written after the V-model colon. The default value is modelvalue
  props:['modelValue','text']
}

3. Remove the. Sync modifier and add a custom V-model modifier

In non custom components, V-model can still be used except. Sync, such as. Lazy,. Trim, etc

//Parent component

  
    
    All the letters in the binding input are uppercase: {message 1}}
    The input letters of binding are all lowercase: {message 2}}
  


//Subcomponents

  
    
    
  


export default {
  props:['modelValue','modelModifiers','text','textModifiers'],
  created(){
    //For V-model binding without parameters, the check object name is modelmodifiers
    //For V-model binding with prop parameter, the check object name is: prop + modelmodifiers
    console.log(this.modelModifiers); //{toUpperCase: true}
    console.log(this.textModifiers); //{toLowerCase: true}
  },
  methods: {
    handleInput1(e){
      let value = e.target.value;
      if(this.modelModifiers.toUpperCase){
        value = value.toUpperCase();
      }
      this.$emit("update:modelValue", value)
    },
    handleInput2(e){
      let value = e.target.value;
      if(this.textModifiers.toLowerCase){
        value = value.toLowerCase();
      }
      this.$emit("update:text", value)
    }
  }
}