vue父子组件通信
vue父子组件通信_父向子-props
步骤:
- 在父组件中向子组件传入相应的数据
- 在子组件中用props接受父组件传入的数据
父组件中的代码
<template>
<div>
<!--
加: 后面是vue变量数据
不加: 后面认为是字符串
-->
<MyProduct title="超级好吃的口水鸡" price="50" :info="msg"></MyProduct>
<MyProduct :title="'超级难吃的榴莲'" :price="20" :info="msg"/>
</div>
</template>
<script>
import MyProduct from './components/MyProduct_13.0'
export default {
data(){
return {
msg: '开业大酬宾, 全场8折'
}
},
components: {
MyProduct
}
}
</script>
子组件中的代码
<template>
<div class="my-product">
<h3>标题: {{ title }}</h3>
<p>价格: {{ price }}元</p>
<p>{{ info }}</p>
</div>
</template>
<script>
export default {
props: ['title', 'price', 'info'] // 声明属性, 等待接收外部传入的值
}
</script>
<style>
.my-product {
width: 400px;
padding: 20px;
border: 2px solid #000;
border-radius: 5px;
margin: 10px;
}
</style>
当然props也可以写成对象的形式以方便对传入的数据进行进一步的要求。
props: {
title: {
type: String // 规定传入的数据的数据类型
required: true // 必传
default: 'hhhh' // 默认值
}
}
单向数据流
在vue中需要遵循单向数据流原则
1. 父组件的数据发生了改变,子组件会自动跟着变
2. 子组件不能直接修改父组件传递过来的props props是只读的
父组件传给子组件的是一个对象,子组件修改对象的属性,是不会报错的,对象是引用类型, 互相更新
总结: props的值不能重新赋值, 对象引用关系属性值改变, 互相影响
vue父子组件通信_子向父-$emit() + 自定义事件
语法:
- 父: @自定义事件名=“父methods函数”
- 子: this.$emit(“自定义事件名”, 传值) - 执行父methods里函数代码
子组件中的代码
<template>
<div class="my-product">
<h3>标题: {{ title }}</h3>
<p>价格: {{ price }}元</p>
<p>{{ info }}</p>
<p>
<button @click="kanFn">砍价</button>
</p>
</div>
</template>
<script>
export default {
props: ['index', 'title', 'price', 'info'], // 声明属性, 等待接收外部传入的值
methods: {
kanFn(){
this.$emit('subprice', this.index, 1)
}
}
}
</script>
<style>
.my-product {
width: 400px;
padding: 20px;
border: 2px solid #000;
border-radius: 5px;
margin: 10px;
}
</style>
父组件中的代码
<template>
<div>
<MyProduct
v-for="(obj, index) in list"
:title="obj.proname"
:price="obj.proprice"
:info="obj.info"
:key="obj.id"
:index="index"
@subprice="fn"
></MyProduct>
</div>
</template>
<script>
import MyProduct from "./components/MyProduct_13.3";
export default {
data() {
return {
list: [
{
id: 1,
proname: "超级好吃的棒棒糖",
proprice: 18.8,
info: "开业大酬宾, 全场8折",
},
{
id: 2,
proname: "超级好吃的大鸡腿",
proprice: 34.2,
info: "好吃不腻, 快来买啊",
},
{
id: 3,
proname: "超级无敌的冰激凌",
proprice: 14.2,
info: "炎热的夏天, 来个冰激凌了",
},
],
};
},
components: {
MyProduct,
},
methods: {
fn(index, price) {
let newPrice = this.list[index].proprice;
newPrice > 1 && (newPrice = this.list[index].proprice - price)
this.list[index].proprice = parseFloat(newPrice.toFixed(2));
},
},
};
</script>
<style>
</style>
总结: 父自定义事件和方法, 等待子组件触发事件给方法传值