vue3-setup语法糖之组件传参(defineProps、defineEmits、defineExpose)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

vue3官方文档 

  • 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>

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue