Vue3語法糖-ref,reactive,onMounted

Vue3.2 版本開始使用語法糖!

script 標籤上寫上 setup!

1
$ <script setup></script>

import { ref,reactive,onMounted } from ‘vue’;

不需寫 return,直接宣告資料

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
<template>
<div id="app">
<h1 v-show="data.sayShow">{{ message }}</h1>
<button @click="open">Say hello.</button>
</div>
</template>

<script setup>
import { ref,reactive } from 'vue';
const message = ref('Hi I am Lara')
const data = reactive({
sayShow: false,
})
const open = () => {
console.log('打開')
data.sayShow = true
}
//TypeScript 型別設定
interface listType {
dt?: number | null,
message?: number | null,
cnt?: number | null,
list:any[]
}

interface weatherType {
cod?: number|null,
message?: number | null,
cnt?: number | null,
list: listType[]
}

const weathers = ref<any>();
//${ import.meta.env.VITE_API_URL }
//${ import.meta.env.VITE_API_KEY }
const getData = async () => {
const api = `${import.meta.env.VITE_API_URL}forecast?q=Taichung,tw&APPID=${import.meta.env.VITE_API_KEY }&lang=zh_tw&units=metric`
try {
const data = await fetch(api);
if (!data.ok) {
throw Error('fetch data 失敗');
}
if (data.status === 200) {
weathers.value = await data.json();
console.log(await data.json())
}
} catch (error) {
// throw Error(error?:any)
}
}


onMounted(() => {
getData();
});
</script>

附上CodePen連結
點擊