iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
Vue.js

從零開始的Vue之旅系列 第 14

vue且試身手-簡易計數器

  • 分享至 

  • xImage
  •  

今天就用vue來寫我們我們個人的一頁式介紹頁面吧
這裡先幫大家回復一下記憶
打開我們的終端機準備開啟專案
輸入cd "專案放置的資料夾位置"
輸入code .打開我們的VSCode
輸入npm run dev啟動本地開發環境預覽頁面
如果是還沒建專案的各位可以參考第四天發的文章

到VSCode開始撰寫計數器程式
先在<script setup>區import{ref},定義變數及函式

<script setup>
import { ref } from 'vue'

const count = ref(0)   // 定義一個「響應式變數」count,初始值是 0

function increment() {   // 定義一個函式,每次點擊按鈕就會讓 count +1
  count.value++
}
</script>

ref(0) 使用ref,vue才能偵測變數的變化並更新畫面。
count.value++ 每次點擊按鈕,變數count就會加一,記得vue是監聽count.value,當.value被修改時vue才能知道狀態改變了,並更新畫面。

接著我們來寫<template>區塊

<template>
  <h1>Vue 計數器</h1>
  <p>目前數字:{{ count }}</p>
  <button @click="increment">+1</button>
</template>

先用標籤<h1>顯示我們的標題
用標籤<p>顯示目前的數字,並利用{{ count }}插值語法顯示不斷更新的count值
<button @click="increment">+1</button> 設置一個button呼叫increment函式,且按鈕的中間會顯示+1

最後在<style scoped>區域設定我們按鈕的樣式

<style scoped>
button {
  padding: 8px 16px;
  font-size: 16px;  //文字大小
  cursor: pointer;  //滑鼠移到該元素上時,顯示成手指指標
}
</style>

記得寫好程式碼後要儲存程式碼喔,簡單按個ctrl+s就可以了
這樣最陽春的基礎介面就設置好了,這裡提醒一下如果預覽畫面沒有變成設定的樣式,可以按左上角的重新載入此頁讓網頁重跑一下,因為實測時我發現,我的畫面有時會變有時不會變
我實在看不慣東西都擠畫面左上角,所以我們來改一點樣式吧
我們先到<template>區域進行更改

<template>
  <body style="display: flex; justify-content: center; align-items: center;height: 100vh; margin: 0; padding: 0;">
    <div class="container">
      <h1>Vue 計數器</h1>
      <p style="font-size: 20px;">目前數字:{{ count }}</p>
      <button @click="increment">+1</button>
    </div>
  </body>
</template>

先用body標籤作為最上層的父元件,設定好style樣式,這樣寫其他元件的style時才能依據父元件設定去更改
再建一個區域包住剛剛建好的元件(標題,文字顯示,按鈕)並設定style名稱為container
接著我們到<style scoped>區域新增其他樣式
直接修改標籤<p>顯示的文字大小

設定container樣式

.container {
  width: 60%;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: rgb(212, 210, 206);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

設定標籤h4樣式

h1 {
  width: 50%;
  height: 60px;
  display: flex;
  background-color: bisque;
  border-radius: 8px;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #5e8b77;
}

好的今天先改到這,至少畫面有點...變化
由上面範例可以發現修改樣式有兩種方法
第一種是Inline style
直接對HTML的標籤上用style:””屬性進行css撰寫

第二種是在<style scoped>區域內先設定好特定名稱的樣式,當HTML標籤套用該名,也會將其樣式套到該區域
如果是對應已存在的標籤只要打上標籤名 ,例如

h1 {
  width: 50%;
  height: 60px;
  display: flex;
  background-color: bisque;
  border-radius: 8px;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #5e8b77;

要使用時只要有標籤就好,例如<h1>Vue 計數器</h1>

如果是要使用自行設定的名稱,名稱前面要記的加一個.
範例

.container {
  width: 60%;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: rgb(212, 210, 206);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

使用時記得要用class=”自行設定的名稱”
<div class="container">

好的時間不早了,各位晚安,明天見~


上一篇
語法介紹part-6-slot
下一篇
vue小專案-代辦事項清單part1
系列文
從零開始的Vue之旅16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言