vue3?setup語法糖之組件傳參(defineProps、defineEmits、defineExpose)示例詳解
defineProps
和defineEmits
都是只能在<script setup>
中使用的編譯器宏。他們不需要導入,且會隨著<script setup>
的處理過程一同被編譯掉。defineProps
接收與props
選項相同的值,defineEmits
接收與emits
選項相同的值。
父傳子 - 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">點擊給父組件傳值</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>
的組件是默認關閉的(即通過模板引用或者 $parent
鏈獲取到的組件的公開實例,不會暴露任何在 <script setup>
中聲明的綁定)。
可以通過 defineExpose
編譯器宏來顯式指定在 <script setup>
組件中要暴露出去的屬性
子組件:
<template> <div> <p>我是子組件</p> </div> </template> <script setup> import { ref } from 'vue'; const stext = ref('我是子組件的值') const sfunction = ()=>{ console.log("我是子組件的方法") } defineExpose({ stext, sfunction }) </script>
父組件:
<template> <div class="todo-container"> <p>我是父組件</p> <son ref="sonDom"></son> <button @click="getSonDom">點擊</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é)點還沒生成 nextTick(()=>{ console.log("sonDom",sonDom.value) }) </script>
到此這篇關于vue3-setup語法糖之組件傳參(defineProps、defineEmits、defineExpose)的文章就介紹到這了,更多相關vue3 setup語法糖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- vue3 setup中defineEmits與defineProps的使用案例詳解
- vue3中defineEmits的使用舉例詳解
- 一文詳細聊聊vue3的defineProps、defineEmits和defineExpose
- Vue3中defineEmits、defineProps?不用引入便直接用
- vue3.0語法糖內的defineProps及defineEmits解析
- vue3中組件事件和defineEmits示例代碼
- vue3使用element-plus中el-table組件報錯關鍵字'emitsOptions'與'insertBefore'分析
- vue3 組合式API defineEmits() 與 emits 組件選項詳解
相關文章
Vue3處理錯誤邊界(error boundaries)的示例代碼
在開發(fā) Vue 3 應用時,處理錯誤邊界(Error Boundaries)是一個重要的考量,在 Vue 3 中實現錯誤邊界的方式與 React 等其他框架有所不同,下面,我們將深入探討 Vue 3 中如何實現錯誤邊界,并提供一些示例代碼幫助理解什么是錯誤邊界,需要的朋友可以參考下2024-10-10Vue開發(fā)中出現Loading?Chunk?Failed的問題解決
本文主要介紹了Vue開發(fā)中出現Loading?Chunk?Failed的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-03-03