×

vue3:聊聊setup语法糖之组件传参

作者:Terry2023.05.28来源:Web前端之家浏览:2075评论:0
关键词: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的值是拿不到的,子组件节点还没生成
	nextTick(()=>{
		console.log("sonDom",sonDom.value)
	})
</script>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vue320230528a23.html

网友评论文明上网理性发言 已有0人参与

发表评论: