Vue父子组件传参

1、父传子

父组件自定义个title属性,绑定要传递的值,子组件通过一个props实例把父组件传递的值获取就可以渲染了。

<template>
  <div>
      <p>父组件</p>
      <con :title="hello"/>
  </div>
</template>

<script>
import con from '../components/componts.vue'
export default {
    name:'login',
    data(){
        return{
            hello:"你的父亲组件"
        }
    },
    components:{
        con
    }
}
</script>

子组件

<template>
  <div class="hello">
      {{title}}
  </div>
</template>

<script>
export default {
  name: 'Compont',
  data(){
      return{}
  },
  props:{
      title:String
  }
}
</script>

注:子组件接受父组件传递过来的是可以定义变量的类型,不是符合类型就不接收

2、子传父

子组件通过点击事件,在点击事件里面自定义个事件
this.$emit(“getdata”,this.test)然后传递给父组件,
父组件接受这个子组件自定义的事件,这个事件有个里面的返回值就是传递过来的数据
<con @getdata=“getdata”/>
子组件

<template>
  <div class="hello">
      <button @click="opee">子传父</button>
  </div>
</template>

<script>
export default {
  name: 'Compont',
  data(){
      return{
        test:"我是儿孩子组件"
      }
  },
  methods:{
      opee:function(){
          this.$emit("getdata",this.test)
      }
  },
}
</script>

父组件

<template>
  <div>
      <p>父组件</p>
      {{msg}}
      <con @getdata="getdata"/>
  </div>
</template>

<script>
import con from '../components/componts.vue'
export default {
    name:'login',
    data(){
        return{ 
            msg:"父组件本来的值"
        }
    },
    methods:{
        getdata(e){
            this.msg=e
            console,log(e)
        }
    },
    components:{
        con
    }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值