0
点赞
收藏
分享

微信扫一扫

vue3语法糖写法组件之间的传值

前端王祖蓝 2022-03-11 阅读 108

踩了很多坑,现在来做个记录,希望看到这篇博客的小伙伴能够避免踩坑

首先父组件传子组件:还是使用v-bind传,然后子组件使用就不一样了,要使用这种方式接收,使用的时候不能直接使用props.mess,要在子组件里面再赋值,再使用

const  props = defineProps ({
  mees:{
    type: String
  }
})
//赋值后,在子组件使用mmm
const mmm = props.mees

然后,父组件要拿到子组件定义的数据,或者触发子组件的方法,要在子组件标签上写ref=“xxxx”,但是在子组件定义的数据和方法一定要使用defineExpose({ msg,fun });暴露出来

<template>
<div>
    <hello ref="chenRef"/>
</div>
</template>
<script setup>
import { ref } from 'vue
import hello from './HelloWorld.vue'

const chenRef = ref(null)
const getc = ()=>{
    //拿到子组件的数据
    console.log(chenRef.value.msg)
    //触发子组件的方法
    chenRef.value.fun()
}
<script>

子组件给父组件传值或者触发父组件方法,要使用自定义事件,下面这个就是简答写法,然后需要在父组件上定义cleck这个是事件,然后在父组件定义cleck要做的事情

<hello @cleck="cleck"/>
子组件
<button @click="$emit('cleck', 'mes')">子组件按钮</button>

也可以不用写在行内,写成这样,在下面在定义,但是这样的话,就要引入defineEmits

<button @click="handle">子组件按钮</button>
import {ref,defineEmits} from 'vue'
const emit = defineEmits (['cleck']) //cleck是父组件自定义事件名

要传值的话,就在数组后面加,'xxxx'

举报

相关推荐

0 条评论