Re-learn the two-way binding between the parent and child components of vue, with detailed code

Description

Insert picture description here

Bind a v-model

Parent component

<template>
    <div>
        <child v-model="parentData"/>
      </div>
</template>
data() {
    
    
      return {
    
     parentData: 1 }
    },

Subcomponent

      <div @click="handleClick">{
   
   {modelValue}}</div>
 //一定只能这样写,modelValue就是parentData
 props: ['modelValue'],
    methods: {
    
    
      handleClick() {
    
    
        //事件名只能是update:modelValue
        this.$emit('update:modelValue', this.modelValue);
      }
    },

Bind multiple v-models

  • You can now change the received name

Parent component

<template>
    <div>
        <!-- 指定传递给子组件的变量名字为newName -->
        <child v-model:newName="parentData"/>
      </div>
</template>

Subcomponent

      <div @click="handleClick">{
   
   {newName}}</div>
 //现在newName就是parentData
 props: ['newName'],
    methods: {
    
    
      handleClick() {
    
    
        //事件名也使用update:newName
        this.$emit('update:newName', this.newName);
      }
    },

Add custom modifiers to v-model

Parent component

<template>
    <div>
        <child v-model.uppercase="parentData"/>
      </div>
</template>

Subcomponent

      <div @click="handleClick">{
   
   {modelValue}}</div>
props: {
    
    
      'modelValue': String,
      'modelModifiers': {
    
    
        default: ()=> ({
    
    })
      }
    },
    methods: {
    
    
      handleClick() {
    
    
        let newValue = this.modelValue + 'b';
        //判断是否有这个东西
        if(this.modelModifiers.uppercase) {
    
    
          newValue = newValue.toUpperCase();
        }
        //注意这个子组件发送给父组件的数据哟
        this.$emit('update:modelValue', newValue);
      },
    }

Guess you like

Origin blog.csdn.net/qq_45549336/article/details/110990794
Recommended