vue3学习笔记第4天

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值