它有助于将问题分解为可以单独解决的较小问题...
组件注册
组件在将其定义导入<script setup> 时会自动注册,因此注册Product 很简单:
<script setup>
import Product from '@/components/Product.vue' // locally registered
</script>
数据属性
反应性数据属性声明为ref(或reactive):
<script setup>
import { ref } from 'vue'
const products = ref([])
const error = ref('')
// to change the value of the `ref`, use its `.value` property
error.value = 'My error message'
products.value = [{ name: 'Product A' }, { name: 'Product B' }]
</script>
或者,您可以在<script setup> 中使用新的/实验性的Reactivity Transform,它全局定义了反应性API,前缀为$(例如,$ref 代表ref),并且避免了解包@ 987654336@s 通过.value:
<script setup>
let products = $ref([])
let error = $ref('')
// assign the values directly (no need for .value)
error = 'My error message'
products = [{ name: 'Product A' }, { name: 'Product B' }]
</script>
created生命周期钩子
<script setup> 块与setup 钩子发生的时间相同,这也与created 钩子的时间相同,因此您可以在那里复制原始钩子代码。要使用await,您可以将调用包装在async IIFE:
<script setup>
import ProductAPI from '@/api/products.api'
import { ref } from 'vue'
const products = ref([])
;(async () => {
products.value = await ProductAPI.fetchAll()
})()
</script>
...或创建一个在其中调用的async 函数:
<script setup>
import ProductAPI from '@/api/products.api'
import { ref } from 'vue'
const products = ref([])
const loadProducts = async () => products.value = await ProductAPI.fetchAll()
loadProducts()
</script>
组件名称
name 属性没有等效的 Composition API,但您可以在同一 SFC 中使用 <script> 块和 <script setup> 来包含 Composition API 不支持的任何道具:
<script setup>
⋮
</script>
<!-- OK to have <script> and <script setup> in same SFC -->
<script>
export default {
name: 'products',
}
</script>
demo