一、props / $emit
父传子,子组件用props接收
子传父,this.$emit
1、子组件代码
<template>
<div class="car">
<p>我是登录页的购物车组件</p>
<p>父组件传递过来的数据:{{ names }}</p>
<button @click="servew">点击我</button>
</div>
</template>
<script>
export default {
// -----------------
props: {
names: {
type: String,
default: "",
},
},
// -----------------
data() {
return {
msg: "我是msg",
msgs: "我是msgs",
};
},
methods: {
servew() {
this.$emit("hahahas", this.msgs);
},
},
};
</script>
<style scoped>
.car {
width: 100%;
height: 400px;
background-color: pink;
}
</style>
2、父组件代码
<template>
<div class="box">
<div @click="home">我是登录页</div>
{{ name }}
<car :names="name" @hahahas="hahaha" ref="childselected"></car>
<p>子组件传递给父组件的数据:{{ number }}</p>
</div>
</template>
<script>
import car from "@/components/car.vue";
export default {
components: {
car,
},
data() {
return {
name: "小米",
number: "",
};
},
mounted() {
this.number = this.$refs.childselected.msg;
},
methods: {
home() {
this.$router.push({
path: "/home",
});
},
hahaha(e) {
console.log(e);
this.number = e;
},
},
};
</script>
<style scoped>
.box {
width: 100%;
height: 100%;
}
</style>
二、$ref可以让父组件更加便利地取到想要的子组件
1、子组件定义数据后无需任何操作
2、父组件中定义ref 并取值