vue-关于子父组件互相传值问题

1.父组件向子组件传值:

 

components: {'child'}引入子组件后,import引入child子组件路径;
return{}中定义->remarkForm:{},
然后,父组件代码:
<template>
  <div v-show="curTab===0">
    <!--子组件child,将remarkForm赋值之后,放入子组件,同时,子组件那边将remarkForm放入prop:{}-->
    <child
         :remarkForm="remarkForm"
    ></cild>
  </div>
<template>
子组件代码:
添加props:{
 remarkForm:{
  type:Object,
 }
}props中的remarkform用于接收父组件的传值

2.子组件向父组件传值:

子组件定义方法,使用$emit声明传值:

<a @on-change='transData(v)'></a>
transData(v){this.$emit('getChildData',v);}

父组件定义接收方法:

return {
 name:'',
}
getChildData(v){
this.name=v;
}
这样就拿到子组件的值了


另外还有一种方法,子组件调用父组件的方法:this.$parent.fatherMethod();
在fatherMethod()中可以给个返回值,子组件需要的返回值

 

 

        

1. 父组件向子组件传值: 在父组件中使用子组件时,可以通过在子组件标签中使用属性绑定的方式将数据传递给子组件。例如: ```html <template> <div> <child-component :prop-name="parentData"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentData: '这是来自父组件的数据' }; } }; </script> ``` 在子组件中,可以通过 `props` 来接收父组件传递过来的数据。例如: ```html <template> <div>{{ propName }}</div> </template> <script> export default { props: { propName: { type: String, required: true } } }; </script> ``` 2. 子组件向父组件传值: 在子组件中,可以通过 `$emit` 方法触发自定义事件,并将数据传递给父组件。例如: ```html <template> <div> <button @click="sendDataToParent">向父组件传递数据</button> </div> </template> <script> export default { methods: { sendDataToParent() { this.$emit('custom-event', '这是来自子组件的数据'); } } }; </script> ``` 在父组件中,可以通过在子组件标签中监听自定义事件的方式接收子组件传递过来的数据。例如: ```html <template> <div> <child-component @custom-event="receiveDataFromChild"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { receiveDataFromChild(data) { console.log(data); // 输出:这是来自子组件的数据 } } }; </script> ``` 3. 父子组件互相传值: 可以将以上两种方式结合起来,实现父子组件互相传值。例如: ```html <template> <div> <child-component :prop-name="parentData" @custom-event="receiveDataFromChild"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentData: '这是来自父组件的数据' }; }, methods: { receiveDataFromChild(data) { console.log(data); // 输出:这是来自子组件的数据 } } }; </script> ``` 子组件: ```html <template> <div> <button @click="sendDataToParent">向父组件传递数据</button> </div> </template> <script> export default { props: { propName: { type: String, required: true } }, methods: { sendDataToParent() { this.$emit('custom-event', '这是来自子组件的数据'); } } }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值