vue3 setup語法糖之父子組件之間的傳值方法
近期學(xué)習(xí) vue3 的父子組件之間的傳值,發(fā)現(xiàn)跟vue2的并沒有太大的區(qū)別,然后發(fā)現(xiàn)網(wǎng)絡(luò)上很少基于setup語法糖的教程,我這邊總結(jié)一下,希望對大家有所幫助。
一、父組件向子組件傳值
父組件向子組件傳值的時候,子組件是通過props來接收的,然后以變量的形式將props傳遞到setup語法糖果中使用(defineEmits的到來?。H缦聢D所示:
1、父組件傳遞方式
<template> <div class="hello"> 我是父組件 <!-- 父組件通過:變量(這里是info)綁定值 --> <Child :info="parentMsg"></Child> </div> </template> <script setup> import Child from './Child' import {ref} from 'vue' const parentMsg=ref('父組件傳遞值是a') </script> <style scoped> </style>
2、子組件接收方式和使用
<template> <!-- info是父組件傳遞過了的值 --> <div>我是子組件拿到了父組件的值是{{info}}</div> </template> <script setup> import { toRefs, defineProps } from 'vue' const props = defineProps({ //子組件接收父組件傳遞過來的值 info: String, }) //使用父組件傳遞過來的值 const {info} =toRefs(props) </script> <style> </style>
3、效果圖
二、子組件向父組件傳值
vue3中子組件向父組件傳遞值和vue2.x的區(qū)別是vue2.x使用的是 $emit 而vue3使用的是emit,它們的傳值一樣都是方法加值,即vue2.x的是this.$emit('方法名','傳遞的值(根據(jù)需要傳或者不傳)'),vue3的setup語法糖的是defineEmits。vue3的子傳父方式如下所示:
1、子組件的傳遞方式
<template> <button @click="clickChild">點擊子組件</button> </template> <script setup> import { defineEmits } from 'vue' // 使用defineEmits創(chuàng)建名稱,接受一個數(shù)組 const emit = defineEmits(['clickChild']) const clickChild=()=>{ let param={ content:'b' } //傳遞給父組件 emit('clickChild',param) } </script> <style> </style>
2、父組件接收與使用
<template> <div class="hello"> 我是父組件 <!-- clickChild是子組件綁定的事件,click是父組件接受方式 --> <Child @clickChild="clickEven"></Child> <p>子組件傳遞的值是 {{result}}</p> </div> </template> <script setup> import Child from './Child' import {ref} from 'vue' const result=ref('') const clickEven=(val)=>{ console.log(val); result.value=val.content } </script> <style scoped> </style>
3、效果圖
三、父組件獲取子組件中的屬性值
當時用語法糖時,需要將組建的屬性及方法通過defineExpose導(dǎo)出,父組件才能訪問到數(shù)據(jù),否則拿不到子組件的數(shù)據(jù)
1、子組件的傳遞方式
<template> <div> <h2> 我是子組件</h2> <p>性別:{{ sex}}</p> </div> </template> <script setup> import { reactive, ref,defineExpose } from "vue"; let sex=ref('男') let info=reactive({ like:'王者榮耀', age:18 }) defineExpose({sex, info}) </script> <style> </style>
2、父組件顯示方式
<template> <div class="hello"> 我是父組件 <Child ref="testcomRef"></Child> <button @click="getSonHander">獲取子組件中的數(shù)據(jù)</button> </div> </template> <script setup> import Child from './Child' import {ref} from 'vue' const testcomRef = ref() const getSonHander=()=>{ console.log('獲取子組件中的性別', testcomRef.value.sex ); console.log('獲取子組件中的其他信息', testcomRef.value.info ) } </script> <style scoped> </style>
3、效果圖
到此這篇關(guān)于vue3 setup語法糖之父子組件之間的傳值的文章就介紹到這了,更多相關(guān)vue父子組件間的傳值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue項目打包部署到GitHub Pages的實現(xiàn)步驟
本文主要介紹了Vue項目打包部署到GitHub Pages的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04在vue中created、mounted等方法使用小結(jié)
這篇文章主要介紹了在vue中created、mounted等方法使用小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07Vue服務(wù)端渲染和Vue瀏覽器端渲染的性能對比(實例PK )
這篇文章主要介紹了Vue服務(wù)端渲染和Vue瀏覽器端渲染的性能對比(實例PK ),非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03