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 的设计理念。

相关推荐
beckyye3 分钟前
阿里云智能语音简单使用:语音识别
前端·语音识别·录音
东东23314 分钟前
前端规范工具之husky与lint-staged
前端·javascript·eslint
jump68017 分钟前
手写事件总线、事件总线可能带来的内存泄露问题
前端
岁月宁静38 分钟前
在 Vue 3.5 中优雅地集成 wangEditor,并定制“AI 工具”下拉菜单(总结/润色/翻译)
前端·javascript·vue.js
执沐41 分钟前
基于HTML 使用星辰拼出爱心,并附带闪烁+流星+点击生成流星
前端·html
atwednesday1 小时前
日志处理
javascript
#做一个清醒的人1 小时前
【electron6】Web Audio + AudioWorklet PCM 实时采集噪音和模拟调试
前端·javascript·electron·pcm
拉不动的猪1 小时前
图文引用打包时的常见情景解析
前端·javascript·后端
浩男孩1 小时前
🍀继分页器组件后,封装了个抽屉组件
前端
Dolphin_海豚1 小时前
@vue/reactivity
前端·vue.js·面试