Vue.js 學習旅程Mile 7 – 資料屬性綁定篇:v-bind


Posted by yuhantaiwan on 2020-04-12

用途

v-bind 來動態綁定 DOM 元素內的屬性值 ( Attributes )

縮寫

可用 縮寫

範例

<div id="app">
  <img id="vueImg" v-bind:src="imgSrc" :class="className" :data="text" alt="">
</div>
var app = new Vue({
  el: '#app',
  data: {
    imgSrc: 'https://images.unsplash.com/photo-1479568933336-ea01829af8de?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=d9926ef56492b20aea8508ed32ec6030&auto=format&fit=crop&w=2250&q=80',
    className: 'img-fluid',
    text: 'Hello!'
  }
})

修飾符 Modifiers

.prop

作為一個 DOM 特性 ( property ) 綁定,而不是作為 屬性 ( attribute ) 綁定。
兩者差別 property v.s. attribute

如果沒有設定修飾符 .prop,綁在 DOM 上面的是 attribute。可以使用 getAttribute 取值。

let element = document.querySelector("#vueImg");
element.getAttribute('data'); // Hello!

但無法利用取 property 的方式取值,拿到的是undefined

element.data;  // undefined

若希望只是存資料待之後運算,並且不希望過份汙染 HTML,通常會設為 property,利用 .prop 改將綁定的屬性設定為 DOM property。

<div id="app">
  <img id="vueImg" v-bind:src="imgSrc" :class="className" :data.prop="text" alt="">
</div>

data 設為 property,在 HTML 上是看不到的。

這樣就可以使用取 property 的方式取值。

let element = document.querySelector("#vueImg");
element.getAttribute('data'); // null
element.data; // Hello!

.camel

若使用 .camel,就會將帶有「-」分隔 (kebab-case) 的屬性名稱轉為小駝峰 (camelCase)。

<div id="svg">
  <svg :view-box.camel="id"></svg>
</div>

.sync

編譯時存在的語法糖,可以擴展成為自動更新父組件屬性的 v-on 監聽器。
待之後談到父子元件傳值時會有詳細介紹。

補充資料

常用寫法範例

<!-- bind an attribute -->
<img v-bind:src="imageSrc">

<!-- dynamic attribute name (2.6.0+) -->
<button v-bind:[key]="value"></button>

<!-- shorthand -->
<img :src="imageSrc">

<!-- shorthand dynamic attribute name (2.6.0+) -->
<button :[key]="value"></button>

<!-- with inline string concatenation -->
<img :src="'/path/to/images/' + fileName">

<!-- class binding -->
<div :class="{ red: isRed }"></div>
<div :class="[classA, classB]"></div>
<div :class="[classA, { classB: isB, classC: isC }]">

<!-- style binding -->
<div :style="{ fontSize: size + 'px' }"></div>
<div :style="[styleObjectA, styleObjectB]"></div>

<!-- binding an object of attributes -->
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

<!-- DOM attribute binding with prop modifier -->
<div v-bind:text-content.prop="text"></div>

<!-- prop binding. "prop" must be declared in my-component. -->
<my-component :prop="someThing"></my-component>

<!-- pass down parent props in common with a child component -->
<child-component v-bind="$props"></child-component>

<!-- XLink -->
<svg><a :xlink:special="foo"></a></svg>

參考資料


#w3HexSchool #Vue #javascript







Related Posts

程式基礎 —— Javascript

程式基礎 —— Javascript

hexo 部署在 AWS S3 上面

hexo 部署在 AWS S3 上面

前後端分離與 SPA

前後端分離與 SPA


Comments