Options API

✐ 特點介紹

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

  • 所有功能依照程式邏輯進行拆分

(資料放 data, 方法放 methods, 運行用 computed, 生命週期)

  • 優點:對於程式初學者容易學習
  • 缺點:商業、功能邏輯會被分散

➤ 載入 CDN

<script src="https://unpkg.com/vue@next"></script>

然後開始初始化 Vue:首先 DOM 會寫一個 id=“app” 的 div,要在哪個範圍裡面 vue.js 都可以有他的功能
(通常大家習慣這樣寫,但 id 可以用其他的值, app 不是絕對的)

<div id="app"> {{ text }} <!-- data 裡面定義的資料屬性 --> <input type="number" v-model="num"> <!-- 指令用法 (v-) --> </div> <!-- DOM 會寫一個 id=“app” 的 div (通常大家習慣這樣寫,但 id 可以用其他的值, app 不是絕對的)--> <script> Vue.createApp({ data(){ return{ text: '我是卡斯伯', // 新增一個 text的 資料屬性名稱 num: 0, // 可以視變數 為一個資料屬性 // v-model 取值,雙向綁定 html 和 data 資料 } }, // data() = data: function() 的縮寫 // 定義資料時,一定是使用 function return 結構 methods:{}, mounted(){}, }).mount('#app') </script>


✐ 使用 createApp 建立起始元件

起手式 1:data 資料邏輯(函式)
起手式 2:methods 方法(物件)
起手式 3:mounted 生命週期(函式)

data(){return{ ... }} 函式

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
重要觀念:先定義資料,才能在 html 中使用

data(){ return { // 這裡就是所有資料(變數 陣列 物件等等) } }
  • 資料可以直接對到畫面,可以把 HTML 拉到資料裡,這就稱為 關注點分離
  • 目前主流三大框架的概念:會習慣性把資料拉出來,用 data 對應資料結構
  • data() = data: function() 的縮寫
  • 定義資料時,一定是使用 function return 的結構
  • 利用 指令v- 也可以把值拉回資料裡面



methods:{} 方法

  • 在 vue 裡面,監聽可以加到畫面上,甚至可以加入一些方法。事件觸發可以直接加在 html上



mounted(){} 生命週期

  • 生命週期的定義:當元素一產生的時候,就會運行 mounted ,只會運行一次,適合用來做初始化資料
  • 取名時 data、methods 不能重複!綠色方塊是運行時
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  • 在 vue 裡面,都用 ,this 取得不同區塊內的的 data 值或是 methods 方法
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
mounted: funtcion() { console.log(this.text); // 用 this 的方式,取得 data 值 this.clickAlert(); // 觸發 clickAlert console.log(this); // 定義的所有資料、方法都會在裡面取得 // this 本身是個很複雜的知識,但在 Vue 中把它簡單化了。 // 修改資料範例 this.text = '我叫小賀' // 初始化行為 // 可以把 Ajax 取得的資料放在這邊 }
  • 可以把 Ajax 取得的資料放在這邊



.mount('')綁定

  • 使用 mount 決定 Vue 的應用程式生成位置
    ​​​​.mount('#app')
tags: Vue3

最後,親愛的大家!我需要你的大聲鼓勵 ٩(⚙ᴗ⚙)۶

如果覺得這篇文章對你有幫助,請給我個一個小小的鼓勵 ❤ 讓我知道,這會成為我寫下去很大的動力。
對了,我還有其他文章,如果有興趣也來逛逛吧!
(文章中如有覺得不妥之處、錯誤內容,也可以透過聯絡我,我會儘速改善,感謝!)

☞ YoJanni 珍妮 2021 正在設計轉職前端的路上,希望大家在學習的路上能夠一起成長
☞ 聯絡我