【vue父子组件传值】

文章介绍了Vue中父子组件如何进行数据传递。父组件通过在子组件标签上设置自定义属性将值传递给子组件,子组件则使用$emit触发事件来向父组件传递数据,事件名和传递的数据可以在父组件的方法中捕获。示例代码展示了具体的实现过程。
摘要由CSDN通过智能技术生成

父传子

在父组件的子标签中写一个自定义属性标签
子组件设置props属性就可以接受父组件传值

子传父

1、在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的
2、子组件可以触发这个事件$emit('事件名字')

子组件给父组件传递数据

$emit方法第二个参数可以定义子组件给父组件传递的内容

在父组件中怎么拿到这内容:

  • 父组件这个方法没有自定参数,在父组件的方法直接加这个参数就可以拿到
  • 父组件有自定义参数,可以传入 event也可以拿到子组件传递的数据。通过$event只能传递第一个参数。
//第一个参数:自定义的名字
//第二个参数:传递的数据
// this.$emit('tofather', '传过去的数据')
 this.$emit('tofather', { name: 'zs', age: 18 })
代码示例
<body>
  <div id='app'>
    <father></father>
  </div>


  <template id="father">
    <div>
      <son :type="type1" @tofather="tofather1(1,$event)"></son>
    </div>
  </template>


  <template id="son">


    <div>son
      <button @click="toFa">toFa</button>
    </div>
  </template>


  <script>
    // 父组件
    Vue.component('father', {
      template: '#father',
      data() {
        return {
          type1: 'free'
        }
      },
      methods: {
        // 接收来自子组件的传值
        tofather1(data, data2) {
          console.log(data);
          console.log(data2);
        }
      }
    })
    // 子组件
    Vue.component('son', {
      template: '#son',
      data() {
        return {
        }
      },
      props: {
        type: {
          type: [String, Number],
          default: () => {
            return 'free'
          }
        }
      },
      methods: {
        toFa() {
          //第一个参数:自定义的名字
          //第二个参数:传递的数据
          // this.$emit('tofather', '传过去的数据')
          this.$emit('tofather', { name: 'zs', age: 18 })
        }
      },
      created() {
        // this.$emit('tofather', { name: 'zs', age: 18 })
        console.log(this.type);
      }
    })
    const vm = new Vue({
      el: '#app',
      data: {
      },
      methods: {
      }
    })
  </script>
</body>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值