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

相关推荐
程序员大阳6 小时前
副队长JavaScript教程(56)-DOM之表单操作
javascript·dom·表单操作
Dxy12393102167 小时前
JS AES加密详解
开发语言·javascript·ecmascript
溪语流沙7 小时前
【每天一个CSS | Day41】开关三连:一套状态机,三种视觉翻译
前端·css·html5·每日一练·按钮
变与不变8067 小时前
css定位布局精讲
前端·css
FRing037 小时前
JavaScript入门到精通三十三(异常处理、call方法、apply方法、bind方法、防抖、节流)
开发语言·前端·javascript
计算机魔术师8 小时前
OpenAI 砍掉 100 亿融资目标,AI 资本市场的温度计变了
前端
jktantan9 小时前
(二)Vue 3 的 attrs 不是响应式:el-form 扩展属性同步的三种方案
前端·javascript·vue.js·element-plus
前端 贾公子9 小时前
第 5 章:Codex 从可运行程序到可交付工具
java·前端·数据库
用户360055579009 小时前
Kestrel_VLLM - 26 · 发射空档三步曲:事件计时 → nsys → 判别实验
前端
echome8889 小时前
JavaScript async/await 错误处理:别让 Promise 静默失败
开发语言·前端·javascript·promise