文章

vue3的选项式api和组合式api

vue3 的 选项式api 和 组合式api

vue3 的 选项式api 和 组合式api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
## 先进的 组合式api

来看看这种先进的写法:48行

```vue
<template>
  <div class="home" v-if="userInfo">
    <my-header />

    用户详情:{{ fullUname }},{{ userInfo.age }}岁

  </div>
</template>
<script setup>// <script setup> 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。
import { ref, onMounted, watch, computed } from 'vue';
import MyHeader from '../components/my-header.vue';

// 属性: 接受属性用户id
const props = defineProps({
  userId: {
    type: String,
    default: '2022-01-01'
  }
})

// 状态:用户信息
const userInfo = ref(null);

// 计算属性:给用户名加一个牛逼的前缀
const fullUname = computed(() => {
  if (userInfo.value && userInfo.value.name) {
    return '牛逼的' + userInfo.value.name;
  }
  return ''
})

// 监听:用户id改变
watch((newVal, oldVal) => {
  console.log('用户id变化啦:' + newVal);
}, { immediate: true })

// 方法:同步用户信息
const syncUserInfo = (userId) => {
  userInfo.value = {
    id: userId,
    name: '小明',
    age: 20
  };
}

// 钩子:初始化
onMounted(() => {
  syncUserInfo(props.userId)
})
</script>

setup() 钩子是在组件中使用组合式 API 的入口,通常只在以下情况下使用:

  1. 需要在非单文件组件中使用组合式 API 时。
  2. 需要在基于选项式 API 的组件中集成基于组合式 API 的代码时。

其他情况下,都应优先使用 **<script setup> 语法。**

本文由作者按照 CC BY 4.0 进行授权