近期學(xué)習(xí) vue3 的父子組件之間的傳值,發(fā)現(xiàn)跟vue2的并沒有太大的區(qū)別,然后發(fā)現(xiàn)網(wǎng)絡(luò)上很少基于setup語法糖的教程,我這邊總結(jié)一下,希望對大家有所幫助。
一、父組件向子組件傳值
父組件向子組件傳值的時候,子組件是通過props來接收的,然后以變量的形式將props傳遞到setup語法糖果中使用(defineEmits的到來?。?。如下圖所示:
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、效果圖
?文章來源地址http://www.zghlxwxcb.cn/news/detail-513304.html
?二、子組件向父組件傳值
vue3中子組件向父組件傳遞值和vue2.x的區(qū)別是vue2.x使用的是 $emit 而vue3使用的是emit,它們的傳值一樣都是方法加值,即vue2.x的是this.$emit('方法名','傳遞的值(根據(jù)需要傳或者不傳)'),vue3的setup語法糖的是defineEmits。vue3的子傳父方式如下所示:?
1、子組件的傳遞方式
<template>
<button @click="clickChild">點(diǎn)擊子組件</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、效果圖
?
三、父組件獲取子組件中的屬性值
當(dāng)時用語法糖時,需要將組建的屬性及方法通過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、效果圖
文章來源:http://www.zghlxwxcb.cn/news/detail-513304.html
?
到了這里,關(guān)于vue3-setup語法糖 - 父子組件之間的傳值的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!