欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-17 15:14:25
说明绑定一个v-model父组件中data() { return { parentData: 1 } },子组件中
{{modelValue}}
...

说明

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

本文地址:https://blog.csdn.net/qq_45549336/article/details/110990794