1️⃣ 使用 setup 语法糖

只需在 script 标签上写上 setup 代码如下(示例):

  1. <template>
  2. </template>
  3. <script setup>
  4. </script>
  5. <style scoped lang="less">
  6. </style>

1️⃣ 引入组件

组件只需引入不用注册

  1. <template>
  2. <div class="app-case">
  3. <chunk-1></chunk-1>
  4. </div>
  5. </template>
  6. <script setup>
  7. import chunk1 from './components/chunk-1.vue'
  8. </script>
  9. <style lang="scss" scoped>
  10. </style>

1️⃣ 属性和方法也不用返回

由于 setup 不需写 return ,所以直接声明数据即可

  1. <template>
  2. <div class="app-case">
  3. {{data1}}
  4. {{data2.a}}
  5. {{a}}
  6. <h1 @click="fun1">fun1</h1>
  7. <h1 @click="fun2">fun2</h1>
  8. </div>
  9. </template>
  10. <script setup>
  11. import {
  12. ref, // 单个数据
  13. reactive, // 多个数据
  14. toRefs, // 数据解构
  15. } from 'vue'
  16. const data1 = ref(100)
  17. const data2 = reactive({
  18. a: 10,
  19. b: 20
  20. })
  21. const { a, b } = toRefs(data2)
  22. function fun1() {
  23. console.log('[ 🎯 fun1]')
  24. }
  25. const fun2 = () => {
  26. console.log('[ 🎯 fun2]')
  27. }
  28. </script>

1️⃣ props 的使用

  1. <template>
  2. <div class="app-case">
  3. <chunk-one :name="name"></chunk-one>
  4. </div>
  5. </template>
  6. <script setup>
  7. import chunkOne from './components/chunk-1.vue'
  8. import { ref } from 'vue'
  9. const name = ref('kun')
  10. </script>
  1. <template>
  2. <div class="chunk-1-case">
  3. {{name}}
  4. </div>
  5. </template>
  6. <script setup>
  7. import { defineProps } from 'vue'
  8. defineProps({
  9. name: {
  10. type: String,
  11. default: '我是默认值'
  12. }
  13. })
  14. </script>