贛州那里有做網(wǎng)站的公司cba排名
<script setup>
是在單文件中使用 Composition API 的編譯時(shí)語(yǔ)法糖,里面的代碼會(huì)被編譯成組件 setup()
函數(shù)的內(nèi)容。
<script setup>
中的代碼在每次組件實(shí)例被創(chuàng)建的時(shí)候都都會(huì)被執(zhí)行。
定義數(shù)據(jù):
在 <script setup>
語(yǔ)法糖的寫(xiě)法中,頂層的綁定會(huì)暴露給模板,因此在 <script setup>
中定義的變量、函數(shù)等可以直接使用。不需要像在 setup()
中一樣 return 返回。
<template><div>{{ message }}</div>
</template><!-- 在 <script setup> 中編寫(xiě) Composition API 就相當(dāng)于是在 setup() 函數(shù)中編寫(xiě) Composition API -->
<script setup>
import {ref} from 'vue'// 在 <script setup> 頂層編寫(xiě)的代碼都會(huì)被暴露給 template 模板,因此在 <script setup> 中定義的變量、函數(shù)等不需要像在 setup() 中一樣 return 返回,可以直接使用
const message = ref('Hello Vue')
</script><style scoped>
</style>
導(dǎo)入組件:
在 <script setup>
語(yǔ)法糖的寫(xiě)法中,導(dǎo)入的組件可以直接使用。不需要像在 setup()
中一樣手動(dòng)通過(guò) components 注冊(cè)。
<template><Home></Home>
</template><script setup>
// 導(dǎo)入的組件不需要像在 setup() 中一樣手動(dòng)通過(guò) components 注冊(cè),可以直接使用
import {Home} from './components/Home.vue'
</script><style scoped>
</style>
接收 props 屬性、發(fā)出 emit 事件:
在 <script setup>
語(yǔ)法糖的寫(xiě)法中,通過(guò) defineProps()
函數(shù)定義要接收的 props;參數(shù)是一個(gè)對(duì)象,定義接收的 props;返回值是一個(gè)只讀的 props 對(duì)象。
defineProps()
函數(shù)默認(rèn)就在當(dāng)前作用域中,不需要導(dǎo)入。
<template><div>{{ name }} - {{ age }}</div>
</template><script setup>
// 通過(guò) defineProps() 函數(shù)定義接收的 props
const props = defineProps({name: {type: String,default: 'Lee',},age: {type: Number,default: 18,}
})
console.log(props)
</script><style scoped>
</style>
在 <script setup>
語(yǔ)法糖的寫(xiě)法中,通過(guò) defineEmits()
定義要發(fā)出的事件;返回值是一個(gè)函數(shù),調(diào)用返回的函數(shù)可以發(fā)出事件。
defineEmits()
函數(shù)默認(rèn)就在當(dāng)前作用域中,不需要導(dǎo)入。
<template><button @cick="handleUserInfoChange">修改</button></template><script setup>// 1. 通過(guò) defineEmits() 定義要發(fā)出的事件const emits = defineEmits(['userInfoChange'])const handleUserInfoChange = () => {// 2. 調(diào)用 defineEmits() 返回的函數(shù)發(fā)出手機(jī)哦啊嗎emits('userInfoChange', '將名字改為 Tom')}</script><style scoped></style>
暴露數(shù)據(jù):
在 <script setup>
語(yǔ)法糖的寫(xiě)法中,組件中的數(shù)據(jù)、方法等如果想要其他組件能夠通過(guò)其組件實(shí)例獲取到,必須通過(guò) defineExpose()
暴露出去。不能像在 setup()
函數(shù)中一樣直接獲取到。
defineExpose()
函數(shù)默認(rèn)就在當(dāng)前作用域中,不需要導(dǎo)入。
// Home.vue
<template><Home ref="homeRef"></Home><button @click="getComponentData">獲取子組件中的數(shù)據(jù)</button>
</template><script setup>
import {ref} from 'vue'
import Home from './components/Home.vue';const homeRef = ref()
const getComponentData = () => {console.log(homeRef.value.message)
}
</script><style scoped>
</style>
// Home.vie
<template>
<div>Home</div>
</template><script setup>const message = 'Hello Vue'
// 組件中的數(shù)據(jù)、方法等如果想要其他組件能夠通過(guò)其組件實(shí)例獲取,必須通過(guò) defineExpose() 暴露出去
defineExpose({message,
})
</script><style scoped>
</style>