1.組合API-setup()
1.組合API的起點(diǎn),將來的組合API的代碼报慕,基本上在這里定義
2.可以理解為:在beforeCreate鉤子執(zhí)行前執(zhí)行,組件實(shí)例創(chuàng)建前
3.函數(shù)中不能使用this ==>undefined
4.模板中需要使用的數(shù)據(jù)宙攻,需要在setup()返回
<template>
<div @click="searchClick">{{ message }}</div>
</template>
<script>
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
components: {},
setup() {
const message = "搜索";
const searchClick = () => {
console.log("搜索成功");
};
return { searchClick, message };
},
});
</script>
<style scoped lang="less"></style>
2.組合AIP-生命周期
認(rèn)識(shí)vue3.0生命周期鉤子函數(shù)
setup 創(chuàng)建實(shí)例前
onBeforeMount 掛載DOM前
onMounted 掛載DOM后
onBeforeUpdate 更新組件前
onUpdated 更新組件后
onBeforeUnmount 卸載銷毀前
onUnmounted 卸載銷毀后
<template>
<div class="container">
container
</div>
</template>
<script>
import { onBeforeMount, onMounted } from 'vue'
export default {
setup () {
onBeforeMount(()=>{
console.log('DOM渲染前',document.querySelector('.container'))
})
//DOM元素渲染后需要執(zhí)行的邏輯
//比如echarts需要將數(shù)據(jù)掛載到DOM中,就需要等DOM元素創(chuàng)建完成再執(zhí)行
onMounted(()=>{
console.log('DOM渲染后1',document.querySelector('.container'))
})
onMounted(()=>{
console.log('DOM渲染后2',document.querySelector('.container'))
})
},
}
</script>
3.組合API-reactive()
定義響應(yīng)式數(shù)據(jù):
reactive是一個(gè)函數(shù)孕锄,它可以定義一個(gè)復(fù)雜數(shù)據(jù)類型,成為響應(yīng)式數(shù)據(jù)苞尝。
用來改變驅(qū)動(dòng)視圖的數(shù)據(jù)
通常用來定義響應(yīng)式數(shù)據(jù)
<template>
<div>
<span>{{ test.name }}</span>
<span>{{ test.age }}</span>
<div @click="editClick()">查看</div>
</div>
</template>
<script>
import { defineComponent, onMounted, ref, reactive } from "vue";
export default defineComponent({
components: {},
setup() {
const test = reactive({
name: "ays",
age: 18,
});
const editClick = () => {
test.name = "xc";
};
return { editClick, test };
},
});
</script>
<style scoped lang="less"></style>