setup(props,ctx){
console.log('props,ctx',props,ctx)
let person = reactive({
name:'张三',
age:20,
sex:'男'
})
return {
person
}
}
// 在父组件中传入参数
<Demo msg="你好啊" name="tom" />
// 在子组件中接收
props:['msg','name'], // 需要声明参数,否则会报警告
setup(props){
console.log(props)
}
1)attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 this.$attrs。如果用props接收了,则会出现在vm上,而attrs中没有
2)emit: 分发自定义事件的函数, 相当于 this.$emit
// 1. 在父组件中给子组件绑定一个事件
<Demo @hello="showHelloMsg">
// 2. 在子组件中触发事件并且可以传值过去
emits:['hello'], // 要声明接收到了hello事件,否则会报警告
context.emit('hello',666)
3)slots: 收到的插槽内容, 相当于this.$slots
<Demo>
<template v-slot:qwe>
<span>你好</span>
</template>
</Demo>
let height = ref(170)
let person = reactive({
name:'张三',
age:20,
sex:'男'
})
name:toRef(person,'name')
const p = toRefs(person)
watch(person,(val,old)=>{
console.log('person is changed',val,old)
})
watch(height,(val,old)=>{
console.log('height2 is changed',val,old)
})
watchEffect(()=>{
let name = person.name
console.log('watchEffect 执行了',name)
})
let full = computed(()=>{
return person.name+'-'+person.age+'-'+person.sex
})
在vue3中,新增了一个setup生命周期函数,setup执行的时机是在beforeCreate生命函数之前执行,因此在这个函数中是不能通过this来获取实例的;同时为了命名的统一,将beforeDestroy改名为beforeUnmount,destroyed改名为unmounted
beforeCreate(建议使用setup代替)created(建议使用setup代替)
setup
beforeMount mounted
beforeUpdate updated
beforeUnmount unmounted
vue3新增了生命周期钩子,我们可以通过在生命周期函数前加on来访问组件的生命周期,我们可以使用以下生命周期钩子:
Composition API 形式的生命周期钩子
onBeforeMount onMounted
onBeforeUpdate onUpdated
onBeforeUnmount onUnmounted
onErrorCaptured
onRenderTracked
onRenderTriggered
<script>
import {
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
ref
} from 'vue'
export default {
setup () {
// 其他的生命周期
onBeforeMount (() => {
console.log("App ===> 相当于 vue2.x 中 beforeMount")
})
onMounted (() => {
console.log("App ===> 相当于 vue2.x 中 mounted")
})
// 注意,onBeforeUpdate 和 onUpdated 里面不要修改值
onBeforeUpdate (() => {
console.log("App ===> 相当于 vue2.x 中 beforeUpdate")
})
onUpdated (() => {
console.log("App ===> 相当于 vue2.x 中 updated")
})
onBeforeUnmount (() => {
console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
})
onUnmounted (() => {
console.log("App ===> 相当于 vue2.x 中 destroyed")
})
return {
}
}
}
</script>
// 在父组件中传入数据
provide('car',car)
//在子孙组件中读取数据
let car = inject('car')
console.log('car',car)
Teleport 是一种能够将我们的组件html结构移动到指定位置的技术
<teleport to="移动位置">
<div v-if="isShow" class="mask">
<div class="dialog">
<h3>我是一个弹窗</h3>
<button @click="isShow = false">关闭弹窗</button>
</div>
</div>
</teleport>
等待异步组件时渲染一些额外内容,让应用有更好的用户体验
用法
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
<template>
<div class="app">
<h3>我是App组件</h3>
<Suspense>
<template v-slot:default>
<Child/>
</template>
<template v-slot:fallback>
<h3>加载中.....</h3>
</template>
</Suspense>
</div>
</template>