vue3 子父组件、组件传值、

目录

父组件给子组件传值

子组件给父组件传值


页面index.vue   子组件footer.vue

父组件给子组件传值

index.vue页面

<div class="box"><!-- 页面使用组件的地方--><!-- parentData 子组件通过 parentData 接收test 要传给子组件的数据--><bottom :parentData = "test"/>
</div>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import bottom from './footer.vue' //引入子组件footer
// test 数据,自己随便定义
const test = ref({id:299709,img_url: "https://res.a.com/pc/common/images/list404.jpg",name: "test",mobile: "10086",
})
</script>

子组件 footer.vue

<div>如果数据不需要处理直接用即可:{{parentData.name}}</div>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'const props = defineProps<{parentData: Object
}>()const newParentData = ref({})
onMounted(() => {//如果js中需要处理父组件传过来的值 // 直接处理数据 props.parentData  重新赋给新newParentData 用即可newParentData.value = 处理后的数据 
})
</script>

子组件给父组件传值

子组件footer.vue

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
// const emit = defineEmits([父组件要接收的key])
const emit = defineEmits(['childData'])
onMounted(() => {setTimeout(()=>{//模拟获取数据//在能获取到值可以传递的放进行传值 emit('childBrokerData', 要传递的值)let jsonData = {name:"test",id:1}  emit('childData', jsonData)},3000)  
})
</script>

父组件 index.vue

<bottom @childData="getChildData"/><script lang="ts" setup>
import { onMounted, ref } from 'vue'
import bottom from './footer.vue' //引入子组件footerconst getChildData = (e) => {console.log(e,'======子组件传过来的数据')
}
</script>