vue3官方文檔?
-
defineProps
?和?defineEmits
?都是只能在?<script setup>
?中使用的編譯器宏。他們不需要導(dǎo)入,且會(huì)隨著?<script setup>
?的處理過程一同被編譯掉。 -
defineProps
?接收與?props
?選項(xiàng)相同的值,defineEmits
?接收與?emits
?選項(xiàng)相同的值。
?
父?jìng)髯? -?defineProps
?父組件
<template>
<div class="Father">
<p>我是父組件</p>
<!-- -->
<son :ftext="ftext"></son>
</div>
</template>
<script setup>
import {ref} from 'vue'
import Son from './son.vue'
const ftext = ref('我是父組件-text')
</script>
子組件
<template>
<div class="Son">
<p>我是子組件</p>
<!-- 展示來自父組件的值 -->
<p>接收到的值:{{ftext}}</p>
</div>
</template>
<script setup>
import {ref} from 'vue'
// setup 語法糖寫法
//defineProps 來接收組件的傳值
const props = defineProps({
ftext: {
type:String
},
})
</script>
子傳父 - defineEmits
子組件:?
<template>
<div class="Son">
<p>我是子組件</p>
<button @click="toValue">點(diǎn)擊給父組件傳值</button>
</div>
</template>
<script setup>
import {ref} from 'vue'
// setup 語法糖寫法
//用defineEmits()來定義子組件要拋出的方法,語法defineEmits(['要拋出的方法'])
const emit = defineEmits(['exposeData'])
const stext = ref('我是子組件的值-ftext')
const toValue = ()=>{
emit('exposeData',stext)
}
</script>
?父組件:
<template>
<div class="Father">
<p>我是父組件</p>
<!-- -->
<son @exposeData="getData" :ftext="ftext"></son>
</div>
</template>
<script setup>
import {ref} from 'vue'
import Son from './son.vue'
const ftext = ref('我是父組件-text')
const getData = (val)=>{
console.log("接收子組件的值",val)
}
</script>
defineExpose
?
?官方解釋:
使用?<script setup>
?的組件是默認(rèn)關(guān)閉的(即通過模板引用或者?$parent
?鏈獲取到的組件的公開實(shí)例,不會(huì)暴露任何在?<script setup>
?中聲明的綁定)。
可以通過?defineExpose
?編譯器宏來顯式指定在?<script setup>
?組件中要暴露出去的屬性
子組件:文章來源:http://www.zghlxwxcb.cn/news/detail-401933.html
<template>
<div>
<p>我是子組件</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const stext = ref('我是子組件的值')
const sfunction = ()=>{
console.log("我是子組件的方法")
}
defineExpose({
stext,
sfunction
})
</script>
父組件:文章來源地址http://www.zghlxwxcb.cn/news/detail-401933.html
<template>
<div class="todo-container">
<p>我是父組件</p>
<son ref="sonDom"></son>
<button @click="getSonDom">點(diǎn)擊</button>
</div>
</template>
<script setup>
import { ref ,nextTick} from 'vue';
import son from './components/son.vue'
const sonDom = ref(null) //注意這里的命名要和ref上面的命名一致
const getSonDom = ()=>{
console.log("sonDom",sonDom.value)
}
//直接打印sonDom的值是拿不到的,子組件節(jié)點(diǎn)還沒生成
nextTick(()=>{
console.log("sonDom",sonDom.value)
})
</script>
到了這里,關(guān)于vue3-setup語法糖之組件傳參(defineProps、defineEmits、defineExpose)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!