1.Vue 3 的 Template 支持多个根标签,Vue 2 不支持
2.Vue 3 有 createApp(),而 Vue 2 的是 new Vue()
createApp(组件),new Vue({template, render})
3.v-model代替以前的v-model和.sync
3.1. props属性名任意,假设为x
3.2. 事件名必须为"update:x"
<Switch :value="y" @update:value="y=$event"/>
vue2中的写法
<Switch :value.sync="y"/>
vue3中的写法
<Switch v-model:value="y"/>
4.context.emit
新增context.emit,与this.$emit(vue3中只能在methods里使用)作用相同
- context.emit用法
import {SetupContext } from 'vue'
setup(props: Prop, context: SetupContext) {
const toggle = () => {
context.emit('input', !props.value)
}
return {toggle}
}
5. Vue3中的属性绑定
默认所有属性都绑定到根元素
使用inheritAttrs: false可以取消默认绑定
使用attrs或者context.attrs获取所有属性
使用v-bing="$attrs"批量绑定属性
使用 const {size, level, …rest} = context.attrs 将属性分开
5.1 使用场景
在vue2中我们在父组件绑定click事件,子组件必须内部触发click,而vue3中在父组件绑定子组件的根元素上也会跟着绑定
- ButtonDemo.vue
<div>
<Button @click="onClick" @focus="onClick" size="small">你好</Button>
</div>
setup() {
const onClick = () => {
console.log("aaa")
}
return {onClick}
},
- Button.vue
<template>
<div>
<button>
<slot/>
</button>
</div>
</template>
上面的代码Button的click事件会在根元素div上绑定,如果我们要指定click的区域为button元素的话我们就需要使用inheritAttrs
- Button.vue
<template>
<div>
<button v-bind="$attrs">
<slot/>
</button>
</div>
</template>
<script lang="ts">
export default {
inheritAttrs: false
}
</script>
如果想要一部分属性绑定在button上一部分在div上就需要在setup里
- Button.vue
<template>
<div :size="size">
<button v-bind="rest">
<slot/>
</button>
</div>
</template>
<script lang="ts">
import {SetupContext} from 'vue'
export default {
inheritAttrs: false,
setup(props: any, context:SetupContext ) {
const {size, ...rest} = context.attrs
return {size, rest}
}
}
</script>