惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
V
Visual Studio Blog
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
IT之家
IT之家
Vercel News
Vercel News
C
Check Point Blog
Google DeepMind News
Google DeepMind News
月光博客
月光博客
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog

韩小韩博客

你还在用真实邮箱注册网站?等等,你真的想清楚了吗? IPFS星际文件系统 最新二合一收款码 - 物理合并版 从Hexo到Astro博客1分钟迁移指南 Astro 添加 Waline 评论组件 腾讯云 EdgeOne Pages 实测对比:能否成为国内开发者的 Cloudflare Pages 最佳平替? Astro 中使用 Lenis 增加鼠标滚动阻尼感 一组手机和电脑动态壁纸分享【分享】 Astro 添加 Twikoo 评论组件 Astro主题-优雅的vhAstro-Theme【使用文档】 Fetch的GET、POST简单HTTP请求封装 一些实拍的手机壁纸 大理And威海【图】 很喜欢西湖的水【转自:狮子狮子鱼】 Tarot-塔罗牌占卜 Web Watermark 图片添加水印在线小助手 HanAnalytics访问分析Web统计托管于(Cloudflare Pages) 基于AI的微博动态心情分析 阿里云免费用9年ecs教程【适合轻量化服务如frp】 Cloudflare优选IP➕DnsPod的DDNS自动切换 混沌神器Clash全家桶 卷王都在用的变态休息法 NodeJs文本相似度去重脚本 骤雨重山无限存储图床托管于(Cloudflare Pages) 分享好看的天空和云(长期更新) Typecho转到Hexo(主题由Typecho-Joe-Theme转Butterfly主题) Typecho评论导出为Hexo的Valine、Twikoo等评论所支持的JSON文件 Safari浏览器内容被地址栏、菜单栏或工具栏遮挡导致的兼容问题 拼夕夕快速提现100元攻略 2024 平安喜乐
Vue 2与Vue 3在自定义组件v-model上的区别
.𝙃𝙖𝙣 · 2026-04-11 · via 韩小韩博客

avatar

.𝙃𝙖𝙣

213 1.1分钟

Code

在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>
Vue Vue3