Vue3 最新setup语法糖

111 阅读1分钟

在使用vue3的最新版本时候,发现官方文档中,可以使用<script setup> 来代替 setup(){} 入口函数。 然而这样有什么用呢?让我们来看看<script setup> 的便捷之处。

1、基本用法

<script setup>
    console.log('hello script setup') 
</script>     

2、绑定函数

<template>
    <button @click=log> log </button>
</template>

<script setup>
    const log = () =>{
        console.log('click log')
    }
</script>     

3、响应式

<template>
    <div>{{num}}</div>
    <button @click=addNum> Count++ </button>
</template>

<script setup>
    import { ref } from 'vue'
    const num = ref(0)
    const addNum = () =>{
        num.value++
    }
</script>     

可以发现我们在绑定方法,和声明响应式数据的时候,不需要再像 setup(){} 那样将数据和方法 return 出去了。

4、使用组件

<template>
    <Son></Son>
</template>

<script setup>
 import Son from './compontent/son.vue'
</script>     

在使用组件的时候无需像之前一样在components中注册组件再使用了,而是直接引入就可以使用。

5、组件传值

子组件

<template>
    <div>{{num}}<div>
    <button @click="handleChange">change<>
</template>

<script setup>
// 子组件接收
 const props = defineProps({
     num: {
         type: Number,
         default: 0
     }
 })
 let param = 10086
 // 注册自定义事件
 const emit = defineEmits(['change'])
 const handleChange = () =>{
     emit('change', param++)
 }
</script>     

父组件

<template>
    <-- 父组件传值 -->
    <Son
     :num="num" 
     @change="handleChange"
    />
</template>

<script setup>
 import Son from './compontent/son.vue'
 import {ref} from 'vue'
 
 const num = ref(0)
 const handleChange = (val) => {
     num.value = val
 }
</script>     

<script setup> 加持下,子组件接收父组件传递的参数可以使用 defineProps({xxx}) 函数,不用vue引入再使用。注册自定义事件也是一样的,直接使用 defineEmits(string[])进行注册使用。

在此附上官网地址

注:自己学习记忆使用,很简单的一些东西,大佬们勿笑