setup写在script标签中

快捷键 vb3s

父组件:

<template>
  <div>
    <child ref="childRef" :title="title" @onTitle="setTitle" />
    <button @click="getChild">获取child实例</button>
  </div>
</template>

<!-- 此写法,它支持顶层async ,在此代码块中你可以直接写await -->
<script setup>
import { ref } from 'vue'
// 导入的组件,导入进来后,直接可以在模板中使用,无须再用 components 注册
import child from './components/child.vue'

let title = ref('我是一个父组件')
let childRef = ref()

const setTitle = tit => (title.value = tit)

const getChild = () => {
  // vue3中的setup很安全,仅仅可以获得实例,获取不到数据
  console.log(childRef.value)
}
</script>

<style lang="scss" scoped>

</style>

子组件:

<template>
  <div>
    <h3>child组件 -- {{ title }}</h3>
    <button @click="setTitle">修改父组件标题</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
// 接受props中的属性
defineProps({
  title: { type: String }
})
// 定义自定义事件
const emit = defineEmits(['onTitle'])

const setTitle = () => {
  // 事件名、数据
  emit('onTitle', Date.now() + '')
}

const name = ref('aaaa')
const fn = () => {}

// 子组件可以选择向外暴露的数据
defineExpose({
  name,
  fn
})
</script>

<style lang="scss" scoped></style>

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值