<script setup> 是Vue 3引入的新特性,用于简化组件的编写,在此代码块里直接使用vue3的语法
vue3官网参考代码
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">
{{ count }}
</button>
</template>
setup() 是Vue 3中的另一种编写组件逻辑的方式。与<script setup>
不同的是,setup()
是一个普通的函数,需要手动引入ref
、reactive
等函数,并返回一个对象,该对象包含组件中需要暴露的响应式数据和方法,在<script>中写setup()的好处是可以同时兼容vue2和vue3两种写法
vue3官网参考代码
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
function increment() {
// 在 JavaScript 中需要 .value
count.value++
}
// 不要忘记同时暴露 increment 函数
return {
count,
increment
}
}
}