vue3 defineProps defineEmits defineExpose

9 篇文章 1 订阅

vue3 defineProps defineEmits defineExpose

defineProps

父组件传值给子组件

defineProps()接受对象,对象的格式如下:

{
	type:String ,// 如果可能存在多个类型,则可以写成 [String,Number]
	default:'默认值',
	required: true// 是否必传 ,在不声明为true 的情况下,所有prop 默认为非必填。
}

子组件child

<template>
 <div>父组件传过来的值: {{ s.title }}</div>
 <div v-for="item in s.arr">{{item}}</div>
</template>

<script setup>
const s=defineProps({
  title: String,
  arr:Array
})
</script>

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

父组件parent

<template>
<child :title="title" :arr="arr"></Child>
</template>

<script setup>
import child from '~/pages/child.vue'
import {ref} from 'vue'
const title=ref("prop父传子")
const arr=ref([1,2,3,4])
</script>

<style lang="scss" scoped>

</style>

image-20220817154439069

defineEmits

子组件向父组件事件传递

defineEmits()接受一个数组,数组内容为父组件自定义的触发事件名称,不是方法名称

emits()第一个参数,是监听事件的字面量。第二个参数为事件传递的参数。如果该事件有多个参数,第二个参数建议用对象的形式传递。

子组件child

<template>
  <button @click="clickThis">点我</button>
</template>

<script setup>
import {ref} from 'vue'
const content=ref("emit事件子传父")
const emit= defineEmits(['someEvent'])
const clickThis = () => {
    emit('someEvent',content.value)
  }
</script>

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

父组件parent

<template>
<child @some-event="callback"></Child>
<div>子向父传值:{{children_msg}}</div>
</template>

<script setup>
import child from '~/pages/child.vue'
import {ref} from 'vue'
const children_msg=ref("")
const callback=(s)=>{
     children_msg.value = s
}
</script>

<style lang="scss" scoped>

</style>

vue3 defineEmits

defineExpose

组件暴露自己的属性,可以通过这个来实现父组件调用子组件的方法,获取子组件的值

父组件parent.vue

<template>
<button @click='childShow'>点击调用子组件方法</button>
<child ref='showComp'></child>
</template>
<script setup>
import { ref } from 'vue'
import child from '~/pages/child.vue'
const showComp=ref(null)//这个时候获取了子组件child
const childShow=()=>{
  showComp.value.show()//调用子组件的show方法
  console.log(showComp.value.count) // 123456
}
</script>

子组件child.vue

<template>
<div>我是子组件</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(123456)
const show=()=>{
  alert("我是子组件,我的show方法被调用了")
}
// 主动暴露childMethod方法
defineExpose({ show,count })
</script>
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值