vue组件传参

一、(父→子)—props传参

(一). 父组件传参

  1. test与子组件props中的参数对应
  2. testData可以是number,string,对象,数组,布尔值,函数
<create-time-count :key="createTimeTimer"  :test="testData"/>
<!-- 函数 -->
<create-time-count :key="createTimeTimer"  @test="testData"/>
data() {
  return {
    //testData: 12312312,//number
    // testData: '字符串',//string
    // testData: {obj: '对象'},//object
    // testData: ['数组'],//object
    // testData: true,//boolean
  }
},
methods: {
  testData() {
    console.log('函数')
  },

(二). 子组件接收参数

props中定义接收的参数,相当于data中的数据,可以在其他地方随意调用。

props: {
  //test:null,
  test:{
	  type: String,//可以注明设置类型,
	  default:'默认值',//默认值,
	  required:false,//是否必须
  }
},
mounted() {
  console.log(typeof(this.test))
  console.log(this.test)
  // this.test()
}

(三). 效果(通过注释代码来校验不同类型的传参)

在这里插入图片描述

(四). 如果testData数据由异步加载来的,子组件渲染完毕,数据才加载出来,所以不做处理的话,子组件无法获取请求到的数据。这时候,引用子组件时需要做一些特殊处理。

1)使用条件加载子组件:当数据不为空时加载子数据

<create-time-count v-if="this.createTimeList.length != 0" :test="testData"/>

2)绑定key值:
a. 通过给子组件绑定一个key,让vue的diff算法可以比较两次key值是否不同,如果key值发生变化,子组件就会重新渲染;
b. key值推荐使用时间戳,随机数也可以。
c. 适用场景:Vue中,在父组件中触发事件,重新渲染子组件(子组件内容会根据数据变化)
html:

<create-time-count :key="createTimeTimer" :test="testData"/>

js:

data() {
  return {
    createTimeTimer: new Date().getTime(),
  }
},
methods: {
   getCreateTimeList() {
      listCreateTime().then(response => {
        this.testData= response.rows;
        this.createTimeTimer = new Date().getTime()
      });
   },
},

参考链接:
https://blog.csdn.net/qq_44375977/article/details/104884834
https://www.jianshu.com/p/4450b63a27fe
https://blog.csdn.net/qq_45625679/article/details/109322460

二、(子→父)—自定义事件

父组件配置

监听子组件的自定义事件closeD,并添加一个响应该事件的处理方法closeDialog
ps: 实际应用建议用同一名词,此处用不同名词只是为了区分

<CallDialog v-if="callDialogShow" :callDialogShow="callDialogShow" @closeD="closeDialog"></CallDialog>
closeDialog(data){
  this.callDialogShow = data;//data==false(子组件传过来的数据)
}

子组件配置

使用$emit来触发一个自定义事件closeD,并传递一个参数false
注:这行代码需要写在事件中才能触发
vue2

this.$emit("closeD", false)

vue3

setup(props, context){
	content.emit("closeD", false)
}

Vue3父子组件emit参数传递(解决Vue2this.$emit无效问题)
参考链接

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值