slot插槽
父组件
<template>
<h3>父亲组件的H3</h3>
<!-- 父组件往子组件传网页代码,使用插槽技术(slot)-->
<Child>
<div>{{msg}}</div>
</Child>
<Child>福州</Child>
<hr>
<Child2>
<template #fz>
<div>福州</div>
</template>
<template #qz>
<div>泉州</div>
</template>
<template v-slot:xm>
<div>厦门</div>
</template>
</Child2>
<hr>
<button @click="test">测试</button>
</template>
<script setup>
import { ref } from 'vue';
import Child from './Child.vue'
import Child2 from './Child2.vue'
const msg = ref("hello world!");
const test = () =>{
msg.value +="abc";
}
</script>
子组件1
<template>
<div class="border:1px solid red">
来自父组件的网页代码:
<slot>no data!</slot>
</div>
<hr>
<!-- 插槽默认值 -->
<slot>no data again!</slot>
</template>
子组件2
实现具名插槽
<template>
<h3>child2</h3>
<slot name="fz"></slot>
<slot name="fz"></slot>
<slot name="xm"></slot>
</template>
父组件向子组件传参
父组件
:pmsg表示传过去的参数名字
<template>
<h3>parent h3</h3>
<Child :pmsg="msg"></Child>
</template>
<script setup>
import { ref } from 'vue';
import Child from './Child.vue'
const msg = ref("this is a book!");
</script>
子组件
defineProps()用于接收父组件传来的值
<template>
<ul>
<li>{{ pmsg }}</li>
</ul>
</template>
<script setup>
defineProps({
pmsg:String
})
</script>
子组件向父组件传参
子组件
<template>
<div>
<h3>child div h3</h3>
<button @click="send">发送信息</button>
</div>
</template>
<script setup>
import { onUnmounted } from 'vue';
const emit = defineEmits(['some-event']);
// 在按钮被点击时触发一个自定义事件,并将消息作为参数传递给父组件。
const send = () => {
emit("some-event","from child's happy message");
}
onUnmounted(()=>{
console.log("child is unmounted is ok!");
})
</script>
父组件
<template>
<h3>c2p parent</h3>
<Child @some-event="show"/>
<hr>
<!-- 从子组件中传来的值 -->
{{ msg }}
</template>
<script setup>
import Child from './Child.vue'
import {onMounted, ref} from 'vue'
const msg = ref("");
const show = (message) =>{
msg.value = message;
}
onMounted(()=>{
console.log("Parent is mounted")
})
</script>