Vue3 中setup()和<script setup><script>

2022-08-01 09:57:16

setup()方法

在组件创建之前执行,是组合式 API 的入口
方法可以接受两个参数 props 和 context

setup方法中,要将数据暴露给页面模板,需要结合ref,和reactive,并使用return
官网例子:

<!-- MyBook.vue -->
<template>
  <div>{{ readersNumber }} {{ book.title }}</div>
</template>

<script>
  import { ref, reactive } from 'vue'

  export default {
    setup() {
      const readersNumber = ref(0)
      const book = reactive({ title: 'Vue 3 Guide' })

      // 暴露给模板
      return {
        readersNumber,
        book
      }
    }
  }
</script>

setup中的生命周期,使用时需要导入
官网例子:

import { onMounted, onUpdated, onUnmounted } from 'vue'

export default {
  setup() {
    onMounted(() => {
      console.log('mounted!')
    })
    onUpdated(() => {
      console.log('updated!')
    })
    onUnmounted(() => {
      console.log('unmounted!')
    })
  }
}

其中beforeCreatecreated 直接写在setup中,官网没有例子

  setup() {
    function fun () {
		console.log("执行!");
	}
	fun();//"执行!"
  }
}

setup标签

使用时要注意vue3版本,好像是3.2开始支持
基本用法,直接在script标签上增加setup

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

数据在页面模板上使用无需 return

<script setup>
import { ref } from 'vue';

// 变量
const msg = ref('Hello!');//响应式数据依然需要ref

// 函数
function log() {
  console.log(msg);
}
</script>

<template>
  <div @click="log">{{ msg }}</div>
</template>

关于组件
引入后直接使用,不需要花里胡哨
官网还有更多关于组件花里胡哨的用法,详见使用组件

<script setup>
import MyComponent from './MyComponent.vue'
</script>

<template>
  <MyComponent />
</template>

顶层await
官网解释:
<script setup> 中可以使用顶层 await。结果代码会被编译成async setup()

<script setup>
	const post = await fetch(`/api/post/1`).then(r => r.json())
</script>

就是在上面使用了await,setup就会变成async setup()

最后
在这里插入图片描述
意思就是,script标签上的 setup 不能和 script标签上的src一起使用(没人会这么干吧应该)

  • 作者:m0_54853420
  • 原文链接:https://blog.csdn.net/m0_54853420/article/details/123369358
    更新时间:2022-08-01 09:57:16