Vue 2与Vue 3在自定义组件v-model上的区别

Vue 2与Vue 3在自定义组件v-model上的区别

HaoOuBa
2021-08-04 / 12 评论 / 1,140 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年08月04日,已超过1087天没有更新,若内容或图片失效,请留言反馈。
在vue开发中,通常会对一个自定义的组件进行封装,并实现v-model双向绑定功能

在 Vue 2 中,通常这样实现

父组件

<template>
  <Child v-model="number"></Child>    
</template>

<script>
  export default {
    data() {
      return {
        number: 0
      }
    },
    components: {
      Child: () => import("./Child.vue")
    }
  }
</script>

子组件

<template>
  <button @click="handleClick">{{ value }}</button>
</template>

<script>
  export default {
    props: {
      value: Number
    },
    methods: {
      handleClick() {
        // 通过emit一个input事件出去,实现 v-model
        this.$emit('input', this.value + 1)
      }
    }
  }
</script>

在 vue 3 中,通过这样实现

父组件

<template>
  <Child v-model="number"></Child>    
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
  setup() {
    const number = ref(0);
    return {
      number
    };
  },
});
</script>

子组件

<template>
  <button @click="handleClick">{{ value }}</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  props: {
    // 更换成了 modelValue
    modelValue: Number
  },
  setup(props, { emit }) {
    // 关闭弹出层
    const handleClick = () => emit('update:modelValue', props.modelValue + 1);
    return { handleClick };
  },
});
</script>
20

评论 (12)

取消
  1. 头像
    meik
    MacOS · Google Chrome

    画图

    回复
  2. 头像
    1
    Windows 10 · Google Chrome

    画图

    回复
  3. 头像
    你的父亲
    Windows 10 · Google Chrome

    画图

    回复
  4. 头像
    炫杰
    Windows 10 · Google Chrome

    画图

    回复
  5. 头像
    Android · Google Chrome

    画图

    回复
  6. 头像
    Money
    Windows 7 · Google Chrome

    网站每日ip 1千,交换友链,https://money1.us/521

    回复
  7. 头像
    你得了痔疮
    MacOS · Google Chrome

    随便写点什么

    回复
    1. 头像
      HaoOuBa 作者
      Windows 10 · Google Chrome
      @ 你得了痔疮

      表情
      牛逼

      回复
    2. 头像
      HaoOuBa 作者
      Windows 10 · Google Chrome
      @ 你得了痔疮

      画图

      回复
  8. 头像
    HaoOuBa 作者
    Windows 10 · Google Chrome

    画图

    回复
    1. 头像
      thug
      iPhone · Google Chrome
      @ HaoOuBa

      画图

      回复
  9. 头像
    555
    Windows 10 · Google Chrome

    画图

    回复