学习vue3的setup的语法糖 script setup

<script setup></script> 

父组件 ↓

<template>
  <div>
    {{ content}}
    <Child ref="childR" aaa='1111' bbb='2222' :name="我是子组件" @clickAction="event" @otherAction="event2">

      <!-- 默认插槽 -->
      <p>默认插槽 content</p>

      <!-- 命名插槽 -->
      <template #slotName>
      <p>命名插槽 content</p>
      </template>

    </Child>
  </div>
</template>

<script setup>
  //  (name不需要定义,使用时以文件名为主)


  // 引入子组件child
  import Child from "./child.vue"
  
  import { ref, onMounted} from 'vue'


  // 直接定义变量content
  let content= "Happy!"
  // 
  let event = () => {
    console.log("触发了父组件事件")
  }
  let event2 = () => {
    console.log("触发了父组件其他操作")
  }
  
  // 获取子组件暴露的数据
  const childR = ref(null)
  onMounted(() => {
    console.log(childR.value.num) // 100
  })
  

  // 直接使用顶层await, 结果代码会被编译成 async setup()
  const post = await fetch(`/list`).then(r =>{})
</script>

子组件 ↓

<template>
  <div>
    {{props.name}}
    <button @click="onClick">点击</button>
    <button @click="onClick2">其他操作</button>
  </div>
</template>

<script setup>
  import { defineExpose, defineProps, defineEmit, useSlots, useAttrs  } from "vue";
  
  
  // 查看父组件自定义的属性
  const attrs = useAttrs() 
  console.log(slots )
  console.log(attrs )  // {aaa: '1111', bbb: '2222'}

  // 获取插槽数据
  const slots = useSlots();
  // 渲染组件
  return () => (
    <div>
      // 渲染默认插槽
      <p>{slots.default ? slots.default() : ""}</p>
      // 渲染命名插槽
      <p>{slots.slotName ? slots.slotName() : ""}</p>
    </div>
  );

  // 使用props和emit
  let props = defineProps({
    name: String,
    age: {
      type: Boolean,
      default: 12,
    },
  });
  let emit = defineEmit(["clickAction","otherAction"]);
  const onClick = () => {
    // 点击触发父组件事件
    emit("clickAction");
  };
  const onClick2= () => {
    // 点击触发父组件其他事件
    emit("otherAction");
  };


  const num = ref(100)
  // 对外暴露 setup 中的数据和方法, 父组件可通过ref访问到
  defineExpose({
    num
  })
</script>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值