iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
自我挑戰組

打造自己的Medium系列 第 6

Day6 Vue基礎篇(上)

  • 分享至 

  • xImage
  •  

雖然ASP.NET Core還沒介紹完,但先開始Vue吧

介紹

  1. SFC: 單一組件的.vue檔案由以下三個區塊組成
    • template: HTML 樣板
    • script: 程式邏輯
    • style: 樣式
  2. Composition API:我覺得相對於options API好理解一點
<script setup>
import { ref, onMounted } from 'vue'

// reactive state
const count = ref(0)

// functions that mutate state and trigger updates
function increment() {
  count.value++
}

// lifecycle hooks
onMounted(() => {
  console.log(`The initial count is ${count.value}.`)
})
</script>
  1. HTML標籤的屬性綁定,是在屬性前加:,從v-bind:<attribute>簡化的語法糖
<template>
  <h1 :class="titleClass">Make me red</h1> <!-- add dynamic class binding here -->
</template>
  1. HTML標籤的事件綁定,是在事件前加@,從v-on:<event>簡化的語法糖
<template>
  <button @click="increment">{{ count }}</button>
</template>

這裡increment是前面function的名稱

  1. 那同時綁state變數和輸入呢?
function onInput(e) {
  // a v-on handler receives the native DOM event
  // as the argument.
  text.value = e.target.value
}
<input :value="text" @input="onInput">

可以直接替換成下面,vue會自動處理onInput的功能,不需要額外寫

<input v-model="text">
// 相當於這種寫法 <input :value="text" @input="e => text = e.target.value">
  1. 條件式邏輯,使用v-if, v-else-if, v-else

範圍限制在v-else需要緊接著v-ifv-else-if

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
  1. 列表渲染
<ul>
  <li v-for="todo in todos" :key="todo.id">
    {{ todo.text }}
  </li>
</ul>

到目前為止,感覺vue就是把一些邏輯卡控直接用前綴v-取代,並且寫在HTML tag裡

對照

框架 Vue React
state定義 const count = ref(0) const [count, setCount] = useState(0)
變更的方式 count.value = newValue setCount(newValue)
讀取值 count count

參考資料

  1. 官方介紹
  2. 官方教學
  3. Using Vue with TypeScript

作者的哈拉

差點忘記發文/images/emoticon/emoticon06.gif,雖然說要寫Vue,但我其實還有考慮用NuxtJS,以Vue為基礎的框架,好像會自動處理路由,有點像以React為基礎的NextJS。


上一篇
Day5 Web API 路由
下一篇
Day7 Vue基礎篇(下)
系列文
打造自己的Medium30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言