通常我們在寫網頁的時候大多直接在標籤加入 class
、id
等關鍵字,但這樣的寫法其實偏向於「寫死」的概念,因此 vue 提供了一種綁定方式為 v-bind
,讓我們可以用動態的方式去綁定,後續要做修改會更方便
eg.
<template>
<div class="box">
<button :class="Direct_binding">測試</button>
</div>
</template>
<script>
export default {
data() {
return {
Direct_binding: 'v-bind-BTN'
// Direct_binding: 'blueBTN'
// Direct_binding: 'redBTN'
}
}
}
</script>
<style scoped>
.box{
border: solid;
margin-left: 850px;
}
.v-bind-BTN{
font-size: x-large;
}
.redBTN{
color: red;
}
.blueBTN{
color: blue;
}
</style>
我先將按鈕的 class 名定義為 Direct_binding
在匯出時期又將其更改,可以看到最後結果是以 v-bind-BTN
為準綁定給該按鈕的 class 名
這邊如果將 class 名改為 blueBTN
或是 redBTN
,則樣式會直接換
先釐清什麼是表達式,簡單來說表達式會產生一個 value
,所以官方文檔才會說「能不能接在 return 後面」是判斷依據。
eg.
1 + 2; // return 3
5 > 4; // return True
再來講一些不是表達式的例子,我們在寫程式的時候都不會把這些語句放在 return
後面
var x = 5; // 陳述式
if (...) // 條件判斷
而 Vue 的模板可以放入 JavaScript 的表達式,直接上例子
<template>
<div>
<!-- 數字運算 -->
<p>{{ 10 + x }}</p> <!-- 顯示 15 -->
<!-- 呼叫 function -->
<p>{{ double(x) }}</p> <!-- 顯示 10 -->
</div>
</template>
<script>
export default {
data() {
return {
x:5
}
},
methods:{
double(x) {
return x * 2
}
}
}
</script>
<style scoped>
div{
text-align: center;
height: 200px;
width: 200px;
border: solid;
margin-left: 500px;
font-size: xx-large;
}
</style>
這邊可以看到
這些模板中的表達式會在 sandbox 的環境下執行,讓它不能隨意去存取整個瀏覽器的全域物件,符合安全機制
今天進度就先到這裡,明天會繼續學習 v-if
的用法!
ref:
https://cn.vuejs.org/guide/essentials/template-syntax.html#using-javascript-expressions
https://medium.com/itsems-frontend/javascript-expressions-and-statements-7bd374effc95
https://zh.wikipedia.org/zh-tw/%E6%B2%99%E7%9B%92_(%E9%9B%BB%E8%85%A6%E5%AE%89%E5%85%A8)