Vue3中模板指令的非兼容变更
按键修饰符
从KeyboardEvent.keyCode has been deprecated 开始,Vue 3 持续反对这一点就不再有意义了。因而,当初倡议对任何要用作修饰符的键应用 kebab-cased (短横线) 大小写名称。
<!-- vue2.x --><input v-on:keyup.13="submit" /><input v-on:keyup.enter="submit" /><!-- vue3.x --><input v-on:keyup.delete="confirmDelete" />
同时废除了全局config.keyCodes选项
key属性
- v-if/v-else/v-else-if的key不再是必须的,vue3.x会主动生成惟一key
不能够通过手动提供key的形式,来强制重用分支
<!-- Vue 2.x 没有必要在vue3.x这样写 --><div v-if="condition" key="yes">Yes</div><div v-else key="no">No</div><!-- Vue 2.x 这在vue3.x中会呈现谬误 --><div v-if="condition" key="a">Yes</div><div v-else key="a">No</div><!-- Vue3.x 如果肯定要指定key,请确保key值不反复 --><div v-if="condition" key="a">Yes</div><div v-else key="b">No</div>
<template v-for>
的key应该设置在<template>
标签上,而不是设置在他的子结点上
<!-- Vue 2.x --><template v-for="item in list"> <div :key="item.id">...</div> <span :key="item.id">...</span></template><!-- Vue 3.x --><template v-for="item in list" :key="item.id"> <div>...</div> <span>...</span></template>
v-if和v-for的优先级调整
这个可太棒了
在vue3中,v-if领有比v-for更高的优先级官网倡议:因为语法上存在歧义,倡议防止在同一元素上同时应用两者。比起在模板层面治理相干逻辑,更好的方法是通过创立计算属性筛选出列表,并以此创立可见元素。
v-bind当初对排序敏感(v-bind的合并行为)
如果在一个元素上同时定义了v-bind="object"和一个雷同的独自的property
那么v-bind的绑定会被笼罩
在vue3.x中 v-bind和独自的property有排序关系,看代码
<!-- vue2.x --><!-- template --><div id="red" v-bind="{ id: 'blue' }"></div><!-- result --><div id="red"></div><!-- vue3.x --><!-- template --><div id="red" v-bind="{ id: 'blue' }"></div><!-- result --><div id="blue"></div><!-- template --><div v-bind="{ id: 'blue' }" id="red"></div><!-- result --><div id="red"></div>
v-on 的 .native 修饰符已被移除
vue3.x中新增了emits选项 对于子组件中未被定义为组件触发的所有事件监听器,Vue 当初将把它们作为原生事件监听器增加到子组件的根元素中 (除非在子组件的选项中设置了 inheritAttrs: false)
<!-- vue2.x --><my-component v-on:close="handleComponentEvent" v-on:click.native="handleNativeClickEvent"/><!-- vue3.x --><my-component v-on:close="handleComponentEvent" v-on:click="handleNativeClickEvent"/><script> export default { emits: ['close'] }</script>
v-for中的ref不再注册ref数组
在 Vue 2 中,在 v-for 里应用的 ref attribute 会用 ref 数组填充相应的 $refs property。当存在嵌套的 v-for 时,这种行为会变得不明确且效率低下。
在 Vue 3 中,这样的用法将不再在 $ref 中主动创立数组。要从单个绑定获取多个 ref,请将 ref 绑定到一个更灵便的函数上 (这是一个新个性)
<div v-for="item in list" :ref="setItemRef"></div><!-- 联合选项式API --><script>export default { data() { return { itemRefs: [] } }, methods: { setItemRef(el) { this.itemRefs.push(el) } }, beforeUpdate() { this.itemRefs = [] }, updated() { console.log(this.itemRefs) }}</script><!-- 联合组合式API --><script>import { ref, onBeforeUpdate, onUpdated } from 'vue'export default { setup() { let itemRefs = [] const setItemRef = el => { itemRefs.push(el) } onBeforeUpdate(() => { itemRefs = [] }) onUpdated(() => { console.log(itemRefs) }) return { itemRefs, setItemRef } }}</script>
itemRefs 不用是数组:它也能够是一个对象,其 ref 会通过迭代的 key 被设置。如果须要,itemRef 也能够是响应式的且能够被监听。