Vue3 setup语法糖学习

  1. 起初 Vue3.0 版本暴露变量必须 return 出来,template中才能使用。
  2. 现在在 vue3.2 版本只需在script标签中添加setup,组件只需引入不用注册,属性和方法也不用返回,也不用写setup函数,也不用写export default ,甚至是自定义指令也可以在我们的template中自动获得。

先来一个小案例尝尝鲜,对比之前的写法少些繁琐的代码,代码看起来更简洁。
在这里插入图片描述

组件自动注册

script setup 中,引入的组件可以直接使用,无需再通过 components 进行注册。示例:

<template>
    <hello-world></hello-world>
</template>

<script setup>
  import helloWorld from './helloWorld'
</script>

因为没有了setup函数,那么props,emit怎么获取呢?setup script语法糖提供了新的API来供我们使用。

新增 API 之 defineProps : 用来接收父组件传来的 props。

defineProps 不再需要引入,可直接使用

父组件:

<template>
  <hello-world :name="name"></hello-world>
</template>

<script setup>
  import helloWorld from './helloWorld'
  import {
    
     ref } from 'vue'
  let name = ref('kk')
</script>

子组件:

<template>
	<div @click="getName">
	    {
    
    {
    
     name }}
	</div>
</template>

<script setup>
const props = defineProps({
    
    
    name:{
    
    
        type:String,
        default:'我是默认值'
    }
})
const getName = ()=>{
    
    
    console.log(props.name)
}
</script>

新增 API 之 defineEmits : 子组件向父组件事件传递。

defineEmits 不再需要引入,可直接使用

父组件:

<template>
   <hello-world @upData="upData"></hello-world>
</template>

<script setup>
  import helloWorld from './helloWorld'
  
  const upData = (data) => {
    
    
    console.log(data); // 我是子组件的值
  }
</script>

子组件:

<template>
  <div>
    我是子组件{
    
    {
    
     name }}
    <button @click="upData">按钮</button>
  </div>
</template>

<script setup>
  // 自定义函数,父组件可以触发
  const em = defineEmits(['upData'])
  const upData=()=>{
    
    
    em("upData",'我是子组件的值')
  }

</script>

新增 API 之 defineExpose : 组件暴露出自己的属性,在父组件中可以拿到。

defineExpose 不再需要引入,可直接使用
父组件:

<template>
  <div class="father">
    <h3 @click="isClick">点击获取子组件数据</h3>
    <hello-world ref="helloWorld"></hello-world>
  </div>
</template>

<script setup>
  import helloWorld from './helloWorld'
  import {
    
    ref} from 'vue'
  const helloWorld = ref()

  const isClick = () => {
    
    
    console.log('接收ref暴漏出来的值', helloWorld.value.age)
    console.log('接收reactive暴漏出来的值', helloWorld.value.user.name)
  }
</script>

子组件:

<template>
   <div>我是子组件</div>
</template>

<script setup>
  import {
    
     reactive, ref } from 'vue'
  let age = ref(18)
  let user = reactive({
    
    
    name:'xiaoli'
  })
  // 暴露出去的变量
  defineExpose({
    
    
    age,
    user
  })
</script>

猜你喜欢

转载自blog.csdn.net/xixihahakkyy/article/details/124940422