vue3-setup语法糖 父子组件传值

新建子组件 Child.vue

一、父组件向子组件传值

父组件向子组件传值的时候,子组件是通过props来接收的,然后以变量的形式将props传递到setup语法糖中使用

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>
 .hello{
   color:red;
  }
</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>

 二、子组件向父组件传值

vue3的setup语法糖的是defineEmits

 1、子组件的传递方式

<template>
  <button @click="clickChild">点击子组件</button>
</template>
 
<script setup>
import { defineEmits } from 'vue'
// 使用defineEmits创建名称,接受一个数组
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>

三、父组件获取子组件中的属性值

当时用语法糖时,需要将组建的属性及方法通过defineExpose导出,父组件才能访问到数据,否则拿不到子组件的数据

 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">获取子组件中的数据</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>

猜你喜欢

转载自blog.csdn.net/weixin_68531033/article/details/128846298
今日推荐