vue v-bind

為組件綁定資料

Juo Penguin
4 min readAug 10, 2020

索引index

一般使用

縮寫 :attr

綁定class/style :class/:style

vue 2.6.0新功能 — 綁定key

.sync

一般使用

<a v-bind:href="link">I am link.</a>({
props: { link: String, }, // link from props
data: { link: YOUR_DATA, } // or from data
})
// 等同於
<a href="YOUR_DATA">I am link.</a>

直接綁定整個object

<div v-bind="{ title: YOUR_TITLE, 'other-attr': otherProps }"></div>// 等同於
<div :title="YOUR_TITLE" :other-attr="otherProps"></div>

綁定自訂component的props

({ 
// ...
name: 'CustomComponent',
props: { yourProp: String, }
})
<CustomCompoent :yourProp="DATA_HERE" />

傳遞整個props給子component

大部分props跟上一層component都一樣時,此方法很好用

// 如果要從上一層傳遞整個$props object給子component,可以這樣做,等同於傳遞this.$props給component<CustomCompoent v-bind="$props" />// 此方法類似react的{...props}
// react
<CustomCompoent {...props} />

使用縮寫

<img :src="imageSrc" :alt="imageName" />// 或是可以使用inline string作為data
<img :src="'/images/icon/' + imageKey" :alt="imageName" />

綁定class/style

class可接受 object, array, array 搭配object

// object用法// 如果isBlackTheme 是 true, 此component就會有.whiteText的class
<span :class="{ whiteText: isBlackTheme }"></span>
// array用法, 此component class="titleText whiteText"
<span :class="[titleText, whiteText]"></span>
// array搭配object用法, 如果isBlackTheme 是 true, 此component class="titleText whiteText"
<span :class="[titleText, { whiteText: isBlackTheme }]"></span>

style可接受object, object[],其中的style properties要用camelCase(例如min-width要用minWidth)

// object
const styleObj = { minHeight: `${200}px` };
<div :style="styleObj"></div>// object[]
const bgStyle = { backgroundColor: '#ddd' };
const titleTextStyle = { color: '#a00' };
<h2 :style="[bgStyle, titleT]"></h2>

綁定key

在vue 2.6.0之後,可以使用動態key來做資料綁定

<div v-bind:[key]="YOUR_VALUE"></div>({ 
data() { return ({ key: 'title', })}
})
// 等同於
<div :title="YOUR_VAlUE"></div>

.sync

為v-bind:PROP + v-on:update:PROP 的語法糖

// CustomImage<img 
:src="imageSrc"
@click="$emit('update:imageSrc', SOME_VALUE)"
>
</div>
({
name: 'CustomImage',
props: { imageSrc: String, }
})
// 使用CustomImage
<div>
<span></span>
<CustomImage :imageSrc.sync="randomImage.src" />
</div>
({
data() {
return ({ randomImage: { src: '', } })
}
})

--

--

Juo Penguin
Juo Penguin

Written by Juo Penguin

不挑食的雜食者,近期的目標是瘦10公斤。

No responses yet