vue2父子组件之间的传值.

目录

摘要:

子组件给父组件传值

子组件传值

父组件接收

父组件给子组件传值

父组件传值

子组件接收

总结要点


摘要:

在 Vue.js 2 中,

父组件向子组件传递数据通常通过属性传递的方式实现,

而子组件向父组件传递数据则通常使用自定义事件的方式。

子组件给父组件传值

$emit 触发事件

  • 子组件通过 $emit 方法触发一个事件,并且可以传递参数。
  • 父组件可以通过监听子组件上 $emit 触发的事件来接收数据。

子组件传值

<template>
  <button @click="sendToParent">Send</button>
</template>
<script>
export default {
  methods: {
     // 点击触发给父组件传值;
    sendToParent() {
      // 使用this.$emit('键','值') 传值;
      this.$emit('custom-event', 'Hello from Child');
    }
  }
}
</script>

父组件接收

<child-component @custom-event="handleMessageFromChild"></child-component>

<script>
export default {
  
  methods: {
    // 使用v-on即简写@ 加 子组件传递的键值接收,可以将接收的值保存在本实列的data()中
    handleMessageFromChild(message) {
      console.log(message);
    }
  }
}
</script>

父组件给子组件传值

props

  • 在子组件中声明接受哪些属性(props)。
  • 在父组件中,通过 <子组件名 :propName="value" /> 的方式将数据绑定到子组件的属性上。

父组件传值

<template>
 <div>
    <child-component :myMessage="'Hello from Parent'" 
                     ref="childInstance"> <!-- 给子组件添加 ref 属性 -->
    </child-component>
    <!-- 调用子组件的方法 -->
    <button @click="callChildMethod">Call Child Method</button>
 </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    callChildMethod() {
      // 通过 ref 访问子组件实例并调用其方法
      this.$refs.childInstance.childMethod();
    }
  }
};
</script>

子组件接收

<template>
  <div>{{ myMessage }}</div>
</template>
<script>
export default {
  props: ['myMessage'],
  // 从子组件获取父组件的实例:this.$parent
  // 可以解构,如:let {tableData} = this.$parent;
}
</script>

总结要点

①Vue.js 中推荐使用 props 进行父组件向子组件的数据传递,

并使用自定义事件($emit)进行子组件向父组件的数据传递。

②此外在子组件中可以使用 this.$parent获取父组件的实例

在父组件中可以给子组件添加ref属性,通过 ref 访问子组件实例并调用其方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值