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

发布时间:2022-07-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue3 中setup()和<script setup></script>脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

SETUP()方法

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

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

<!-- 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()

最后

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

意思就是,script标签上的 setup 不能和 script标签上的src一起使用(没人会这么干吧应该

脚本宝典总结

以上是脚本宝典为你收集整理的Vue3 中setup()和<script setup></script>全部内容,希望文章能够帮你解决Vue3 中setup()和<script setup></script>所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。