vue2实现父子组件传值

vue2实现父子组件传值

<在Vue 2中,父子组件之间的通信有多种方式,其中最常用的包括通过props传递数据(从父到子)和通过自定义事件(从子到父)。下面我将分别介绍这两种方法。

通过Props传递数据(从父到子)

在Vue 2中,你可以通过props将数据从父组件传递到子组件。

父组件可以将在方法中变化的变量传递给子组件
父组件(ParentComponent.vue)

<template>
  <div>
    <ChildComponent :message="parentMessage" :topData = "topData" />
  </div>
</template>
 
<script>
import ChildComponent from './ChildComponent.vue';
 
export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentMessage: 'Hello from parent',
      topData: "",
    };
  },
  methods: {
		changeTopData(){
			this.TopData = new_data
		}
	}
}
</script>

子组件需要相应方法实现上级传输数据与本地数据的绑定,并监听上级传输数据的变化
子组件(ChildComponent.vue)

<template>
  <div>
    <p>{{ message }}</p>
    <input v-model="localData"></input>
  </div>
</template>
 
<script>
export default {
  //props: ['message']
  props: {
	message: {
		type: String,
		default: "",
	},
	topData: {
		tyep: String,
		default: "",
	}
},
data(): {
	return: {
		localData: "",
	}
 },
//实现上级传入数据复制给本地数据
mounted() {
this.localData = this.topData
} ,
//监听数据变化
watch: {
topData(val) {
		this.localData = val
		}
	}
}
</script>

通过自定义事件传递数据(从子到父)

在Vue 2中,你可以通过自定义事件将数据从子组件传递到父组件。

父组件(ParentComponent.vue)

<template>
  <div>
    <ChildComponent @child-event="handleChildEvent" />
  </div>
</template>
 
<script>
import ChildComponent from './ChildComponent.vue';
 
export default {
  components: {
    ChildComponent
  },
  methods: {
    handleChildEvent(data) {
      console.log('Received from child:', data);
    }
  }
}
</script>

子组件(ChildComponent.vue)

<template>
  <div>
    <button @click="sendToParent">Send to Parent</button>
  </div>
</template>
 
<script>
export default {
  methods: {
    sendToParent() {
      this.$emit('child-event', 'Hello from child');
    }
  }
}
</script>

使用.sync修饰符(父子双向绑定)

在Vue 2中,你可以使用.sync修饰符来实现父子组件之间的双向绑定。这种方法主要用于更新父组件中的数据。注意,.sync修饰符实际上是v-bind和v-on的语法糖。它背后使用的是事件来更新父组件的数据。但需要注意的是,.sync修饰符在Vue 3中已经被移除,推荐使用v-model配合事件来实现类似功能。在Vue 2中,你可以这样做:

父组件(ParentComponent.vue)使用.sync修饰符:

<template>
  <div>
    <ChildComponent :message.sync="parentMessage" /> <!-- 使用 .sync -->
  </div>
</template>

在子组件中,你需要触发一个更新事件来更新父组件的数据:

this.$emit('update:message', newValue); // 在Vue 2中,这种方式等同于Vue 3的
### Vue 中动态组件与父子组件之间 #### 使用 `v-bind` 和 `$emit` 实现父到子以及子到父的通信 在 Vue 中,可以利用 `<component>` 元素配合 `is` 属性来定义动态组件。对于父子组件间的通讯,则可以通过 `props` 将数据从父级递给子级,并通过自定义事件 (`$emit`) 来让子组件向父组件发送消息。 ```html <!-- ParentComponent.vue --> <template> <div class="container"> <!-- 动态切换显示不同的子组件 --> <button @click="currentTab = 'compA'">Show Comp A</button> <button @click="currentTab = 'compB'">Show Comp B</button> <!-- 渲染当前选中的组件并递参数 --> <component :is="currentTab" :message="parentMsg"></component> <!-- 接收来自子组件的消息 --> <p>Received message from child: {{ receivedMessage }}</p> </div> </template> <script> import CompA from './components/CompA.vue'; import CompB from './components/CompB.vue'; export default { name: "ParentComponent", components: { CompA, CompB }, data() { return { currentTab: 'compA', parentMsg: 'Hello from Parent!', receivedMessage: '' } }, methods: { handleChildEvent(msg) { this.receivedMessage = msg; } } } </script> ``` 上述代码展示了如何在一个名为 `ParentComponent` 的父组件内使用两个按钮控制不同子组件(`CompA`, `CompB`)之间的切换[^2]。这里的关键在于: - **动态渲染**:通过设置 `:is=currentTab` 让 Vue 根据变量 `currentTab` 的决定要加载哪个组件。 - **属性绑定**:`:message=parentMsg` 表达式用于将父组件的数据作为 prop 发送给被激活的那个子组件实例。 为了完成完整的双向交互模式,还需要考虑子组件如何响应这些 props 并反馈信息回给父组件。下面是一个简单的子组件模板: ```html <!-- ChildComponent.vue (通用结构适用于 CompA 或者 CompB)--> <template> <div> <h3>{{ title }}</h3> <input type="text" v-model="localCopyOfProp"/> <br/> <span>(This value comes from the parent)</span> </div> </template> <script> export default { props: ['message'], computed: { localCopyOfProp: { get() { return this.message; }, set(newValue) { // 当输入框内容改变时触发更新事件通知父组件 this.$emit('update:message', newValue); } } }, mounted(){ console.log(this.message); } }; </script> ``` 这段脚本说明了当用户修改输入框内的文本时,会调用 `set()` 方法并通过 `$emit` 向外发出一个带有新的通知。这样就形成了闭环式的双向绑定机制[^1]。 此外,如果想要更进一步处理非直系关系下的跨层组件交流问题,比如祖孙三代甚至多代之间的沟通需求,那么 Vuex 或者提供 / 注入 API 可能是更好的解决方案[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值