2024-12-25
前端开发
00

目录

父组件给子组件传值
父组件代码
子组件代码
子组件给父组件传值(通过方法)
父组件代码
子组件代码

父组件给子组件传值

  • 父组件将对象或数组传到子组件的方法
  • 子组件如何拿数组接受父组件传来的数组
  • 子组件如何在父组件传入数值变更的时候触发事件 watch

父组件代码

js
<template> <div> <子组件名称 :ceshidata1="ceshidata1" :ceshidata2="ceshidata2"></子组件名称> </div> </template> <script setup> //引入子组件 import 子组件名称 from './components/子组件名称.vue' const ceshidata1 = ref('66666') const ceshidata2 = ref([{name:"11111",value:3},{name:"222222",value:4}]) </script>

子组件代码

js
<template> <div> {{props.ceshidata1}} {{props.ceshidata2}} </div> </template> <script setup> import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'; let props = defineProps(['ceshidata1','ceshidata2']); //数组 | 对象写法都可以 const datalist = [...props.ceshidata2] //如果需要做筛选可以拿数组接收 onMounted(() => { //可以直接使用 console.log(props.ceshidata1); console.log(props.ceshidata2); }) //watch监听有新值传入的时候触发方法 watch(props, (newValue) => { console.log(newValue); }); </script>

子组件给父组件传值(通过方法)

父组件代码

js
<template> <div> <子组件名称 @textff="textff" ></子组件名称> </div> </template> <script setup> //引入子组件 import 子组件名称 from './components/子组件名称.vue' const textff = (e)=>{ console.log(e,"子组件传来的值") } </script>

子组件代码

js
<template> <div @click="chuanzhi("123123")"> 页面内容 </div> </template> <script setup> import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'; let emit1 = defineEmits(['textff']); //数组|对象写法都可以 const chuanzhi = (e)=>{ //传值给父组件 emit1('textff', e); } </script>
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:烈焰大火龙

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 © 烈焰大火龙 许可协议。转载请注明出处!