vue3的语法
1.vue3基本結(jié)構(gòu)
vue3可以導(dǎo)入本地版本或者在線版本
1.1 vue3創(chuàng)建根組件
vue2中的vue是一個(gè)構(gòu)造函數(shù),創(chuàng)建根組件用new關(guān)鍵字創(chuàng)建
const vm = new Vue({})
vue3中vue是一個(gè)對(duì)象,創(chuàng)建根組件如下:
const app = Vue.createApp({})
1.2 vue3引入根標(biāo)簽
app.mount(“#myApp”)
vue3使用mount()函數(shù)渲染組件模板,作用相當(dāng)于vue2的el屬性
1.3 setup函數(shù)
vue3中新增了一個(gè)setup函數(shù),相當(dāng)于生命周期函數(shù),他會(huì)在beforeCreate之前被調(diào)用,所以setup中不能使用this
setup(props) {console.log("setup", this) // window},vue3廢除了filters過(guò)濾器,不再支持此語(yǔ)法
2,vue3生命周期
2.1 創(chuàng)建vue3代碼片段
vscode打開(kāi),文件–首選項(xiàng)–用戶片段—新建全局代碼片段–MyVue3,創(chuàng)建之后在文件中復(fù)制以下代碼即可:
{"vue3": {"scope": "html","prefix": "myVue3","body": ["<script src='https://unpkg.com/vue@next'></script>","<div id='myApp'>","\t","</div>","<script>","\tvar vm = {","\t\tsetup() {","\t\t\t","\t\t}","\t}","\tVue.createApp(vm).mount('#myApp')","</script>",],"description": "這是我的vue3結(jié)構(gòu)的代碼片段"} }2.2 vue3生命周期
vue2中的生命周期寫(xiě)法,vue3可兼容。vue3中把生命周期全部放在setup函數(shù)中實(shí)現(xiàn)
- vue3中創(chuàng)建過(guò)程的兩個(gè)鉤子已經(jīng)被廢除,銷(xiāo)毀前和銷(xiāo)毀后鉤子被改成onbeforeUnmount、onUnmounted
- vue3中調(diào)用生命周期鉤子用到組合式API(Hook inside)
- vue3鉤子之間不能用逗號(hào),否則會(huì)報(bào)錯(cuò)
調(diào)用生命周期鉤子如下:
setup(a,b,c) {Vue.onBeforeMount(() => {console.log("beforeMount")});Vue.onMounted(() =>{console.log("mounted")})Vue.onBeforeUpdate(() => {console.log("beforeUpdate")})Vue.onUpdated(() => {console.log("updated")})Vue.onBeforeUnmount(() => {console.log("beforeUnmount")})Vue.onUnmounted(() => {console.log("unmounted")})}2.3 vue3定義動(dòng)態(tài)數(shù)據(jù)
vue2中使用data定義數(shù)據(jù),定義后用this調(diào)用并修改, 但是setup中不能用this, 所以vue3中的動(dòng)態(tài)數(shù)據(jù)不要在data中定義了,在setup中定義
Vue.ref定義動(dòng)態(tài)數(shù)據(jù),setup中所有的變量或函數(shù)都需要在return中返回才能在模板中調(diào)用
const age = Vue.ref(0)- 通過(guò)Vue.ref定義的數(shù)據(jù),會(huì)被放入對(duì)象的value字段中
- 使用對(duì)象調(diào)用value字段才是動(dòng)態(tài)數(shù)據(jù)
- vue3響應(yīng)式數(shù)據(jù)在setup中使用Vue.ref()定義, 會(huì)包裹一層對(duì)象, 在js中使用時(shí),調(diào)用value屬性, 模板中不需要調(diào)value
2.4 vue3定義函數(shù)
const add = ()=>{ }總結(jié)
 
                            
                        - 上一篇: 二叉树的中序遍历和后序遍历算法
- 下一篇: 行人重识别的代码复现
