重学vue之父子组件间的双向绑定,附详细代码

说明

在这里插入图片描述

绑定一个v-model

父组件中

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

子组件中

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

绑定多个v-model

  • 现在可以更改接收的名称了

父组件中

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

子组件中

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

为v-model添加自定义修饰符

父组件中

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

子组件中

      <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);
      },
    }

猜你喜欢

转载自blog.csdn.net/qq_45549336/article/details/110990794