1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > vue3 - 10.父子子父组件传值 ref获取方法

vue3 - 10.父子子父组件传值 ref获取方法

时间:2022-03-30 06:49:52

相关推荐

vue3 - 10.父子子父组件传值 ref获取方法

// 用vue3+ts实现父子组件声明,父子组件传值,子父组件传值,父组件获取子组件声明的方法,父组件修改(添加)子组件样式,并且灵活应用ref,reactive,toRaw,defineProps,defineEmits,defineExpose,以及ts声明字符串,数值,数组,对象类型

<template><div><box ref="getBox" :data="data" @getChildData="handleChild" /><button @click="handleClick">点击获取ref调取子组件的方法</button></div></template><script setup lang='ts'>import { reactive, ref } from 'vue'import box from './box.vue'let index = ref<number>(0)// 父组件获取子组件的调用函数方法const getBox = ref<InstanceType<typeof box>>()const handleClick = () => {// 获取子组件的方法名let isFn = getBox.value?.handleSubmit()if(!isFn){console.log("获取到了")}// 给子组件增加样式let dom = getBox.value?.$el as HTMLElementdom.className = 'box'// 修改子组件的值dom.innerText = `hello - ${String(index.value++)}`}// 父组件给子组件传值type info = {name:string,age:number,sex:boolean}const data = reactive<info>({name:"xiaoming",age:22,sex:true})// 获取子组件传过来的值const handleChild = (data:string) => {console.log(data)}</script><style scoped lang=less>.box {width:100px;height:100px;background: #f00;}</style>

<template><div><div>hello</div>父组件传过来的值:{{getData.data}}<button @click="handleChildData">点击给父组件传值</button></div></template><script setup lang='ts'>import { ref,toRaw } from 'vue'const msg = ref<number[]>([1,2,3,4,5])// 接收子组件传过来的值type Props = {data:object}const getData = defineProps<Props>()// 给父组件传值const emits = defineEmits(['getChildData'])const handleChildData = () => {let arr = toRaw(msg.value)console.log("点击给父组件传值 =>",arr)emits('getChildData','hellow123')}// 在子组件定义方法const handleSubmit = () => {console.log('hello-world')}// 抛出方法,只有抛出方法,父组件的ref才能获取得到defineExpose({handleSubmit})</script>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。