
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>



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