vue 父子组件进行传参

父子组件进行传参

父传子

原理:父控制子,通过子组件的props属性,抛出子组件自定义标签属性,来接收父组件的操作状态。

// 父
<template>
 <div>
<child-module :content="content"/>
 </div>
</template>
<script>
import ChildModule from '@/components/ChildModule.vue'
export default {
 name: 'FatherModule',
 components: {
   ChildModule
 },
 data() {
   return {
     content: "text"
   }
  }
}
</script>
// 子
<template>
 <div>
 <div>{{ content }}</div>
 </div>
</template>
<script>
export default {
 name: 'ChildModule',
 props: {
 content: {
   // 定义接收的类型 还可以定义多种类型 [string,Undefined,Number]// 如果required为true,尽量type允许undefined类型,因为传递过来的参数是异步的。或者设置默认值
   type: String,
   // 定义是否必须传
   required: true,
   // 定义默认值
   default: '暂⽆'
   }
 }
}
</script>

子传父

原理:子控制父,子组件绑定自定义事件,来处理父组件的方法函数,通过.$emit(‘自定义事件’,[参数]) 来触发属于自己的自定义事件。

// 父
<template>
 <div>
 <child-module
 ref="childModuleRef"
 :content="content"
 @getData="getData"/>
 <div>{{ childValue }}</div>
 </div>
</template>
<script>
import ChildModule from '@/components/ChildModule.vue'
export default {
 name: 'FatherModule',
 components: {
   ChildModule
 },
 data() {
   return {
     content: "text",
     childValue: ''
   }
 },
 methods: {
 // childrenData就是⼦组件传递过来的参数
   getData(childrenData) {
   console.log(childrenData)
   this.childValue = childrenData
   }
 }
}
</script>
// 子
<template>
 <div>
 <div>{{ content }}</div>
 <button @click="onClick">点击向⽗组件传参</button>
 </div>
</template>
<script>
export default {
 name: 'ChildModule',
 props: {
   content: {
     type: String,
     required: true,
     default: '暂⽆'
   },
 },
 data() {
   return {
     num: 1
   }
 },
 methods: {
   onClick() {
    this.$emit("getData",this.num)
   }
 }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值