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

相关推荐
玫城5 小时前
[ VUE ] 封装通用数组校验组件,el-input内使用
前端·javascript·vue.js
弓.长.9 小时前
React Native 鸿蒙跨平台开发:实现一个多功能单位转换器
javascript·react native·react.js
南半球与北海道#10 小时前
前端打印(三联纸票据打印)
前端·vue.js·打印
摘星编程10 小时前
React Native for OpenHarmony 实战:ToggleSwitch 切换开关详解
javascript·react native·react.js
董世昌4110 小时前
深入浅出 JavaScript 常用事件:从原理到实战的全维度解析
前端
满栀58510 小时前
分页插件制作
开发语言·前端·javascript·jquery
qq_4061761410 小时前
深入剖析JavaScript原型与原型链:从底层机制到实战应用
开发语言·前端·javascript·原型模式
弓.长.11 小时前
React Native 鸿蒙跨平台开发:BottomSheet 底部面板详解
javascript·react native·react.js
开开心心_Every11 小时前
免费窗口置顶小工具:支持多窗口置顶操作
服务器·前端·学习·macos·edge·powerpoint·phpstorm
摘星编程11 小时前
React Native for OpenHarmony 实战:Permissions 权限管理详解
javascript·react native·react.js