Vue父组件向子组件传参

父组件传参给子组件:

 

1.在父组件data中定义要传给子组件的参数

  data () {
    return {
      fathermsg: '100000086666'
    };
  }

2.在父组件中调用子组件,并在components中注册

import zizuj1 from '../component/zizujian1';

export default {
  components: {
    zizuj1
  }

3.在父组件中引用子组件,把父组件的值绑定给子组件(msgFromfather1可以写为msg-fromfather1)

<zizuj1 :msgFromfather1="fathermsg" msgFromfather2="父传子的参数"></zizuj1>

4.在子组件props定义接收的参数名

<template>
  <div>
    <p>{{msgFromfather1}}</p>
    <p>{{msgFromfather2}}</p>
  </div>
</template>
<script>
export default {
  name: 'zizujoo',
  props: [
    'msgFromfather1',
    'msgFromfather2'
  ],
  mounted () {
    console.log(this.msgFromfather1);
    console.log(this.msgFromfather2);
  }
};
</script>

整理一遍流程:

1.在父组件data中定义要传给子组件的参数

2.在父组件中调用子组件,并在components中注册

3.在父组件中引用子组件,把父组件的值绑定给子组件(msgFromfather1可以写为msg-fromfather1)

4.在子组件props定义接收的参数名

 

Vue中,组件向子组件传递参数有多种方式,以下是其中两种常用的方式: 1. Props 属性传递:组件通过在子组件的标签上绑定属性的方式传递数据。在子组件中,通过 props 选项接收组件传递的属性值。 组件示例: ```vue <template> <div> <child-component :message="message"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { data() { return { message: 'Hello from parent component' }; }, components: { ChildComponent } }; </script> ``` 子组件示例(ChildComponent.vue): ```vue <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { props: ['message'] }; </script> ``` 2. 使用 $emit 事件进行通信:组件可以通过触发子组件的自定义事件,传递需要的参数。子组件可以通过 $emit 方法触发该事件,并将参数传递给组件组件示例: ```vue <template> <div> <child-component @custom-event="handleEvent"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { methods: { handleEvent(data) { console.log('Received data:', data); } }, components: { ChildComponent } }; </script> ``` 子组件示例(ChildComponent.vue): ```vue <template> <div> <button @click="triggerEvent">Send Event</button> </div> </template> <script> export default { methods: { triggerEvent() { this.$emit('custom-event', 'Data from child component'); } } }; </script> ``` 这两种方式都可以实现组件向子组件传递参数,具体选择哪种方式取决于你的需求和场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值