Vue – 變數的擺放位置

標籤中

在標籤中的變數可以使用雙括弧。

<div class="app">
	<a href="">{{google.link}}</a>
</div>
new Vue({
	el: '.app',
	data: {
		google: {
			link: 'http://google.com'
		}
	}
})

輸出

<div class="app">
        <a href="">http://google.com</a>
</div>

 

標籤屬性中

變數在屬性中不可使用雙括弧 {{ }}。關於 v-bind 不太懂的地方,可以參考 在標籤中,綁定參數 (v-bind) 與監聽事件 (v-on) 的混和用法

<div class="app">
	<a href="{{google.link}}">{{google.link}}</a> <!-- 錯誤 -->
	<a v-bind:href="google.link">{{google.link}}</a> <!-- 正確-->
</div>
new Vue({
	el: '.app',
	data: {
		google: {
			link: 'http://google.com'
		}
	}
})

輸出

<div class="app">
	<a href="{{google.link}}">http://google.com</a> <!-- 無法解析而顯示字串 -->
	<a href="http://google.com">http://google.com</a> <!-- 正確 -->
</div>

 

變數應用在 Vue.component 組件的情況

把上面的改成組件的寫法,進一步解說可以參考 Vue.component 組件教學 – 使用 v-bind、v-for

單筆資料簡單範例

<div class="app">
	<c-website v-bind:item="google"></c-website>
</div>
Vue.component('c-website', {
	props: ['item'],
	template: '<a v-bind:href="item.link">{{item.link}}</a>'
})

new Vue({
	el: '.app',
	data: {
		google: {
			link: 'http://google.com'
		}
	}
})
輸出
<div class="app">
	<a href="http://google.com">http://google.com</a>
</div>

多筆資料進階範例

<div class="app">
	<ul>
		<c-website v-bind:item="val" v-for="val in website"></c-website>
	</ul>
</div>
Vue.component('c-website', {
	props: ['item'],
	template: '<li><a v-bind:href="item.link">{{ item.title }}</a></li>'
})

new Vue({
	el: '.app',
	data: {
		website: {
			google: {
				title: 'Google',
				link: 'http://google.com'
			},
			yahoo: {
				title: 'yahoo',
				link: 'http://tw.yahoo.com'
			}
		}
	}
})
輸出
<div class="app">
	<ul>
		<li>
			<a href="http://google.com">Google</a>
		</li>
		<li>
			<a href="http://tw.yahoo.com">yahoo</a>
		</li>
	</ul>
</div>

 

 

發表迴響