Lala Code

Lala 的前端大補帖,歡迎一起鑽研前端技術😊

0%

Vue3 自定義模板 directive

全局 directive

透過 directive 可以讓每頁都使用共用語法,在 main.js 中添加全局 directive
directive mounted 生命週期等同於 onMounted, 但這裡為純 js 並非 vue 的週期裡,所以這樣使用

main.js

1
2
3
4
5
6
7
8
9
10
11
const app = createApp(App);

// 自定義變數名稱focus
app.directive("focus", {
mounted(el) {
console.log(el);
el.focus(); // 有v-focus名稱的都會有focus()效果
},
});

app.mount("#app");

template

1
<input v-focus type="text" /> // 自定義變數名稱前面須加上前綴v-XXX

範例: 將數字轉千分位

tool.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export const numPrice = (num) => {
const n = num + "";
const numArr = n.split("").reverse();
const overArr = [];
let i = 0;
numArr.forEach((item) => {
i++;
if (i > 3) {
i = 1;
overArr.push(",");
}
overArr.push(item);
});
overArr.reverse();
return overArr.join("");
};

main.js
mounted(el, val) // 第二個參數為 v-xxx=”丟進去的值”

1
2
3
4
5
6
7
8
9
10
11
12
13
import { createApp } from "vue";
import App from "./App.vue";
import { numPrice } from "@/lib/tools.js";
const app = createApp(App);

app.directive("price", {
mounted(el, binding) {
const p = numPrice(binding.value);
el.innerHTML = p;
},
});

app.mount("#app");

template

1
<h1 v-price="15555000"></h1>

加上 v-model 時需 updated

因為 mounted 只會執行一次,如需動態綁定,需再加上 updated
main.js

1
2
3
4
5
6
7
8
9
10
app.directive("price", {
mounted(el, binding) {
const p = numPrice(binding.value);
el.innerHTML = p;
},
updated(el, binding) {
const p = numPrice(binding.value);
el.innerHTML = p;
},
});

components

1
2
3
4
5
6
7
8
9
import { ref } from "vue";
export default {
setup() {
const num = ref(1233211234567);
return {
num,
};
},
};
1
2
<input v-model="num" type="text" />
<h1 v-price="num"></h1>

以上是我的學習筆記,希望也有幫助到你哦 😀



Hey!想學習更多前端知識嗎?

最近 Lala 開了前端課程 👉【實地掌握RWD - 12小時新手實戰班】👈
無論您是 0 基礎新手,又或是想學 RWD 的初學者,
我們將帶你從零開始,深入了解並掌握 RWD 響應式網頁設計的核心技術,快來一起看看吧 😊



🚀線上課程分享

線上課程可以加速學習的時間,省去了不少看文件的時間XD,以下是我推薦的一些課程
想學習更多關於前後端的線上課程,可以參考看看。

Hahow

Hahow 有各式各樣類型的課程,而且是無限次數觀看,對學生或上班族而言,不用擔心被時間綁住



六角學院

如果你是初學者,非常推薦六角學院哦!
剛開始轉職也是上了六角的課,非常的淺顯易懂,最重要的是,隨時還有線上的助教幫你解決問題!


Udemy

Udemy 裡的課程非常的多,品質普遍不錯,且價格都滿實惠的,CP值很高!
也是很多工程師推薦的線上課程網站。
❤️