1.父向子传值
//--->Father.vue
<template>
<div id="father">
<p>黄色为父组件---data的值为:{{ data }}</p>
<Son>
<template #usname>
<p>data的值为:{{data}}</p>//将父组件的data数据传入子组件的<slot>插槽
</template>
</Son>
</div>
</template>
<script>
import Son from "./Son.vue";
export default {
data() {
return {
data: "Father",
};
},
components: {
Son,
},
};
</script>
<style scoped>
#father {
width: 400px;
height: 400px;
background-color: yellow;
}
</style>
//--->son.vue
<template>
<div id="son">
<p>蓝色为子组件</p>
<slot name="usname"></slot>
</div>
</template>
<script>
export default {};
</script>
<style scoped>
#son {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
2.子向父传值
//--->Father.vue
<template>
<div id="father">
<p>黄色为父组件---data的值为:{{ data }}</p>
<button @click="upp">1</button>//点击查看传过来的值
<Son>
<template #usname="obj">//通过v-slot指令接收son.vue传过来的值
<p>data的值为:{{ data }}</p>
<p>son_data的值为{{ obj.son }}</p>
<button @click="son_data = obj.son">1</button
>//通过点击按钮将传过来的值保存在Father组件的son_data数据中
</template>
</Son>
</div>
</template>
<script>
import Son from "./Son.vue";
export default {
data() {
return {
data: "Father",
son_data: "",
};
},
components: {
Son,
},
methods: {
upp() {
console.log(this.son_data);
},
},
};
</script>
<style scoped>
#father {
width: 400px;
height: 400px;
background-color: yellow;
}
</style>
//--->Son.vue
<template>
<div id="son">
<p>蓝色为子组件</p>
<slot name="usname" :son='son_data'></slot>//添加自定义属性son将son_data数据传入父组件
</div>
</template>
<script>
export default {
data(){
return{
son_data:'Son'
}
}
};
</script>
<style scoped>
#son {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>