vue2 vue3父子组件传参

vue3 父子组件传参

父组件

<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
import { onMounted, ref } from 'vue'
// 传给子组件的值 在引用的组件里传递参数
const list:Array<number> = [1,2,3,4]


//  接收子组件的值  先用ref获取子组件
const HelloWorldRef = ref()
// 组件挂载时调用 onMounted
onMounted(()=>{
  console.log(HelloWorldRef.value.toFather);
})

</script>

<template>
<div>
  <HelloWorld :list="list" ref="HelloWorldRef" />
</div>
  
</template>

<style>
</style>

子组件

<script setup lang="ts">
import { ref } from "vue"

//  接收父組件的傳值 defineProps
// 第一種方法  默认值
const props = defineProps({
    list:{
        type: Array,
        default:() => [4,5,6]
    }
})
//  第二種方法 没有默认值
//  先定义接口 interface
interface Props {
  list: Array<number>;
}
const props =  defineProps<Props>()

// 父传子还有一种方法  可以参考上一篇vue2 vue3调用方法 


// 传给子组件的值 先用defineExpose导出子组件的值
const toFather = ref('子组件的值')
defineExpose({toFather})
</script>

<template>
 <div>
  HelloWorld
 </div>
</template>

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

vue2父子组件传参

父组件

<template>
  <div class="home">
<!--    :list 向子组件传递参数  @fromSon是子组件自定义的方法-->
    <HelloWorld :list="toSon" @fromSon="fromSon"/>
    <button @click="changeToSon">改变传递的参数</button>
  </div>
</template>

<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'HomeView',
  components: {
    HelloWorld
  },
  data(){
    return {
      toSon: [1,2,3]
    }
  },
  methods:{
    // 改变传递的参数 触发子组件的监听事件watch
    changeToSon(){
      this.toSon = [4,5,6]
    },
    // 接收子组件的参数
    fromSon(data){
      console.log(data)
    }
  }
}
</script>

子组件

<template>
  <div class="hello">
    HelloWorld
    <button @click="toFather">传参给父组件</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data(){
    return {
      msg: '子组件的值'
    }
  },
  // 接收父组件传递的参数
  props:{
    list:{
      type: [Array,String],
      default(){
        return [7,8,9]
      }
    }
  },
  // 监听事件 监听父组件传递参数改变
  watch:{
    list:{
      handler(oldValue,newValue){
        console.log(oldValue)
        console.log(newValue)
      },
      deep: true
    }
  },
  created() {
    console.log(this.list)
  },
  methods:{
  // 传递给子组件的方法
  toFather(){
    // 第一个参数自定义的方法,第二个参数为传递的参数
    this.$emit('fromSon',this.msg)
  }
}

}
</script>

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值