vue2中this.$emit(“update:xx“,value)和xx.sync的用法在vue3中有什么变化

在 Vue 3 中,v-model 语法和 this.$emit("update:xx", value) 的用法略有变化,而 .sync 修饰符已经不再存在。下面是 Vue 2 中和 Vue 3 中的比较:

Vue 2 中的写法:

使用 this.$emit("update:xx", value)
javascript 复制代码
<!-- ChildComponent.vue -->
<template>
  <input :value="value" @input="updateValue" />
</template>

<script>
export default {
  props: ['value'],
  methods: {
    updateValue(event) {
      this.$emit('update:xx', event.target.value);
    }
  }
};
</script>
javascript 复制代码
<!-- ParentComponent.vue -->
<template>
  <child-component :xx.sync="parentValue" />
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentValue: ''
    };
  }
};
</script>

Vue 3 中的写法:

使用 v-model:xx
javascript 复制代码
<!-- ChildComponent.vue -->
<template>
  <input v-model:xx="value" />
</template>

<script>
export default {
  props: ['value']
};
</script>
javascript 复制代码
<!-- ParentComponent.vue -->
<template>
  <child-component v-model:xx="parentValue" />
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentValue: ''
    };
  }
};
</script>

在 Vue 3 中,推荐使用 v-model:xx 来简化双向绑定的语法。这样的写法更加直观和简洁,更好地符合 Vue 3 的设计理念。

相关推荐
美团技术团队11 分钟前
报名 | 美团技术沙龙第86期:多业务场景下,美团如何做性能优化
前端
Rrvive41 分钟前
localhost 和 127.0.0.1 的核心区别
前端
蓝倾41 分钟前
如何使用Python通过API接口批量抓取小红书笔记评论?
前端·后端·api
極光未晚43 分钟前
JavaScript BOM 对象:浏览器的隐形控制塔
前端·javascript·源码
天涯学馆1 小时前
网站秒变 App!手把手教你搞定 PWA
前端·javascript·面试
uu_code0071 小时前
Android接入Pixelfree美颜SDK技术指南
前端
小鱼小鱼干1 小时前
使用 ESLint 实现 Git Commit 前的语法检查
前端
用户9272472502191 小时前
PHP + CSS + JS 数据采集与展示系统
javascript
码哥DFS1 小时前
Flex布局原理
前端·css·css3
小样还想跑1 小时前
axios无感刷新token
前端·javascript·vue.js