Vue3父子通訊方式及Vue3插槽的使用方法詳解
在Vue3中父子通訊方式
Vue3父傳子(props)
父組件如下:
<template> <div class="about"> <h1>This is an about page</h1> <children :num="num" age="30"></children> </div> </template> <script> import children from "../components/children.vue"; import { ref } from "vue"; export default { setup() { let num = ref("《nanchen》"); return { num, }; }, components: { children, }, }; </script>
子組件如下:
<template> <div>我是子組件 我的父組件值為:{{ yy }}</div> </template> <script> import { ref } from "vue"; export default { name: "Vue3appChildren", props: { num: { type: Number, }, }, setup(props) { let yy = ref(props.num); return { yy, }; }, mounted() {}, methods: {}, }; </script> <style lang="scss" scoped> </style>
setup中的參數(shù)分別有:
props:值為對象,包含:組件外部傳遞過來,且組件內(nèi)部聲明接收了的屬性。
context:上下文對象
attrs: 值為對象,包含:組件外部傳遞過來,但沒有在props配置中聲明的屬性, 相當(dāng)于 this.$attrs。
slots: 收到的插槽內(nèi)容, 相當(dāng)于 this.$slots。
emit: 分發(fā)自定義事件的函數(shù), 相當(dāng)于 this.$emit
props中可以接收父組件傳遞給子組件的參數(shù)
Vue3子傳父({emit})
父組件:
<template> <div class="about"> <h1>This is an about page</h1> <children :num="num" age="30" @test="showHello"></children> </div> </template> <script> import children from "../components/children.vue"; import { ref } from "vue"; export default { setup() { let num = ref("《nanchen》"); function showHello(value) { console.log(value); } return { num, showHello, }; }, components: { children, }, }; </script>
子組件
<template> <div @click="aboutClick">我是子組件 我的父組件值為:{{ yy }}</div> </template> <script> import { ref } from "vue"; export default { name: "Vue3appChildren", props: { num: { type: Number, }, }, setup(props, { emit }) { let yy = ref(props.num); function aboutClick() { emit("test", "你好你好"); // 子傳父 } return { yy, aboutClick, }; }, mounted() {}, methods: {}, }; </script> <style lang="scss" scoped> </style>
點擊div效果如下:
Vue3插槽
<children :num="num" age="30" @test="showHello"> <h1>南辰,Hello</h1> </children>
<template> <div @click="aboutClick">我是子組件 我的父組件值為:{{ yy }}</div> <slot></slot> </template>
具名插槽的寫法
<slot name="aabb"></slot>
<HelloWorld> <template v-slot:aabb> <span>NanChen,你好</span> </template> <!-- <template #aabb> <span>NanChen,你好</span> </template> --> </HelloWorld>
到此這篇關(guān)于Vue3父子通訊方式及Vue3插槽的使用方法詳解的文章就介紹到這了,更多相關(guān)Vue3父子通訊方式及Vue3插槽的使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Vue3+Three.js實現(xiàn)一個3D模型可視化編輯系統(tǒng)
這篇文章主要介紹了基于Vue3+Three.js實現(xiàn)一個3D模型可視化編輯系統(tǒng),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09Vue利用AJAX請求獲取XML文件數(shù)據(jù)的操作方法
在現(xiàn)代Web開發(fā)中,從前端框架到后端API的交互是必不可少的一部分,Vue.js作為一個輕量級且功能強大的前端框架,支持多種方式與服務(wù)器通信,從而獲取或發(fā)送數(shù)據(jù),本文將詳細介紹如何在Vue.js項目中使用AJAX請求來獲取XML格式的數(shù)據(jù),需要的朋友可以參考下2024-09-09vue.js 圖片上傳并預(yù)覽及圖片更換功能的實現(xiàn)代碼
這篇文章主要介紹了vue.js 圖片上傳并預(yù)覽及圖片更換功能,小編主要圍繞我們?nèi)粘J褂霉δ艿睦幼鲋v解,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08elementui中el-row的el-col排列混亂問題及解決
這篇文章主要介紹了elementui中el-row的el-col排列混亂問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08