reactive響應(yīng)式
1.對(duì)象類(lèi)型
import { reactive, toRefs } from "vue";
const user = reactive({
name: 'Vue2',
age: 18,
});
user.name = 'Vue3';
let {name}=toRefs(user);//解構(gòu)時(shí)需要用toRefs,否則會(huì)消除響應(yīng)式
2基本類(lèi)型
const num = ref(0);//定義初始值
num.value++;
defineProps
const props = defineProps<{
size: string;
name: string;
}>();//父?jìng)髯訉傩灾?console.log(props.id)//不加props.拿不到值
<span>{{id}}</span><--!組件使用時(shí)不用加props.-->
defineEmits
// 定義Emits(子組件)
const emits = defineEmits<{
(e: 'add', id: number): void
}>()
const btnAdd = () => {
emits('add',2)
}//子組件調(diào)用父組件方法add()
//父組件
<child @add="add"><child/>
<script setup lang="ts">
const add = (num:number)=>{
result.value+=num
}
</script>
父子組件通訊
- 父?jìng)髯?/li>
父組件:
<Son :money="money"/>
子組件:
<span>{{money}}</span>
props:{
money:{
type:string,
default:0
}
}
//在setup中使用
setup(props){
console.log(props.money)
}
- 子傳父
子組件:
<button @click="changeMoney">改變</button>
setup(props,{emit}){
const changeMoney=()=>{
emit("change-money",20)
}
}
父組件
<Son :money="money" @change-money="getSon"/>
//語(yǔ)法糖:v-model="money"
const getSon=(m)=>{
money.value=m
}
- 子組件調(diào)用父組件方法
父組件
<Son :count="count" @changeCount="changeCount"/>
const changeCount=(val)=>{
count.value=val;
}
子組件
const emit=defineEmits(['changeCount']);
const changeCount=()=>{
emit('changeCount',5)
}
- 父組件調(diào)用子組件方法
子組件
const ChildFn=(v)=>{
console.log(v)
}
defineExpose({ChildFn})
父組件
<Son ref="sonRef"/>
<button @click="getChild">change</button>
const sonRef=ref(null)
const getChild=()=>{
sonRef.value.ChildFn("hello")
}
provide 和 inject 注入依賴(lài)
provide("count",count)//注入變量
//注入方法
const changeVal=(n)=>{
count.value=n
}
provide("changeVal",changeVal)
const count = inject('count');//接收變量
//接收方法
const changeVal= inject('changeVal');
const fn=()=>{
changeVal(20)
}
生命周期
setup():開(kāi)始創(chuàng)建組件,在beforeCreate 和 created 之前執(zhí)行,創(chuàng)建的是 data 和 method
onBeforeMount():組件掛載到節(jié)點(diǎn)上之前執(zhí)行的函數(shù)
onMounted():組件掛載完成后執(zhí)行的函數(shù)
onBeforeUpdate():組件更新之前執(zhí)行的函數(shù)
onUpdated():組件更新完成之后執(zhí)行的函數(shù)
onBeforeUnmount():組件卸載之前執(zhí)行的函數(shù)
onUnmounted():組件卸載完成后執(zhí)行的函數(shù)
onActivated():被 keep-alive緩存的組件激活時(shí)調(diào)用。
onDeactivated(): 被 keep-alive緩存的組件停用時(shí)調(diào)用
onErrorCaptured():當(dāng)捕獲一個(gè)來(lái)自子孫組件的異常時(shí)激活鉤子函數(shù)。
vue2和vue3的區(qū)別
- 響應(yīng)式原理不同,vue2:Object.definePropty();vue3:proxy()
- diff算法不同
- 生命周期不同
- vue2:選項(xiàng)式api(Options API),組合式api(Composition API)
- vue3支持碎片(Fragments)
vue2和vue3diff算法的區(qū)別
- Vue 2 的 diff 算法會(huì)對(duì)整個(gè) DOM 樹(shù)進(jìn)行完整的比較
- 但在vue3中,增加了靜態(tài)標(biāo)記。在創(chuàng)建vnode的時(shí)候,會(huì)根據(jù)vnode的內(nèi)容是否可以變化,為其添加靜態(tài)標(biāo)記,靜態(tài)標(biāo)記會(huì)根據(jù)不同的標(biāo)簽具有不同的值。這樣diff的時(shí)候,只需要比較靜態(tài)標(biāo)記變化了的節(jié)點(diǎn),要比對(duì)的內(nèi)容更少了
keepAlive原理
keepAlive將滿(mǎn)足條件的VNode節(jié)點(diǎn)保存在this.cache中,在render時(shí),如果VNode的name符合緩存條件(可以用include以及exclude控制),則會(huì)從this.cache中取出之前緩存的VNode實(shí)例進(jìn)行渲染。