组件之间数据是独立的 可以通过一定步骤实现组件之间的数据传递
1、子传父
1.1第一步:父组件中通过自定义属性传递
<Test name='133' :age='age'></Test>
data(){
return {
age:13
}
},
1.2第二步:子组件通过props指定接受
export default {
props:['name','age']
}
<template>
<div>
{{name}}
{{age}}
</div>
</template>
1.3总写:以把字符串和变量传给子组件为例
父组件代码
<template>
<div>
<MyProduct title="好吃的口水鸡" price='88' intro="跳水价"></MyProduct>
<MyProduct :title="title" :price='price' :intro="intro"></MyProduct>
</div>
</template>
<script>
import MyProduct from "@/componets/MyProduct";
export default {
components: {
MyProduct,
},
data() {
return {
title: "好吃的口水鸡",
price:88,
intro:'跳水价'
};
},
};
</script>
<style>
</style>
子组件代码
<template>
<div>
<template>
<div class="my-product">
<h3>标题: {{ title }}</h3>
<p>价格: {{ price }}元</p>
<p>{{ intro }}</p>
</div>
</template>
</div>
</template>
<script>
export default {
props: ["title", "price", "intro"],
};
</script>
<style>
.my-product {
width: 400px;
padding: 20px;
border: 2px solid #000;
border-radius: 5px;
margin: 10px;
}
</style>
1.4把数据遍历给子组件
可以在父组件里遍历
<MyProduct v-for="item in list" :key="item.id" :obj='item'></MyProduct>
props: ['obj'],
也可以在子组件里遍历
<MyProduct :obj='item'></MyProduct>
<div class="my-product" v-for="obj in list" :key="obj.id">
2、父传子
2.1第一步:子触发自定义事件
<button @click="fn">click</button>
methods: {
fn() {
this.$emit("on-send", this.fName);
},
},
fName: 999,
2.2第二步:父接受子传过来的内容
import Child from "@/componets/Child";
components: {
Child,
},
<Child @on-send='sendFn'></Child>
methods:{
sendFn(val){
console.log('子传父'+val);
}
}
2.3单向数据流
2.3.1父组件把数据传递给子,子接收使用
2.3.2父组件修改数据 数据向下流动到子组件 子组件在当前部分实现数据驱动视图
3、兄弟组件之间通信
数据提升:把子组件数据上传到父组件
组件通信:兄弟之间传参 eventBus
bus.$emit('xxx',99)
bus.$on('xxx',(res)=>{
console.log(res)
})
兄弟传参步骤
1、创建One.vue Two.vue引入父组件
App.vue代码
<template>
<div>
<One></One>
<Two></Two>
</div>
</template>
<script>
import One from "@/components/One";
import Two from "@/components/Two";
export default {
components: {
One,
Two,
},
};
</script>
<style>
</style>
2、在子组件中添加样式
One.vue
<div class="box">
One
<button @click="btnFn">点击发送数据给two</button>
</div>
.box{
width: 300px;
height: 100px;
border: 1px solid #ccc;
background-color: greenyellow;
}
Two.vue
<div class="box1">two</div>
.box1 {
width: 300px;
height: 100px;
border: 1px solid #ccc;
background-color: green;
}
3、在与main.js同目录下创建eventbus.js
import Vue from 'vue'
let bus =new Vue()
export default bus
4、在组件中导入eventbus.js
import bus from '@/eventbus.js'
5、把One组件中的值传入Two组件中
methods:{
btnFn(){
bus.$emit('on-send','我是one的数据')
}
}
created(){
bus.$on('on-send',(res)=>{
console.log('我在two接收数据:'+res);
})
}
本文详细介绍了Vue中如何实现子组件向父组件传递数据(props)、父组件向子组件传递数据($emit)、以及兄弟组件间的通信方法,包括数据提升和eventBus的应用。实例演示了如何在组件间有效地传递和共享数据。
3025

被折叠的 条评论
为什么被折叠?



