iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 12
0
Modern Web

Vue.js 30天系列 第 12

Vue.js 12 - 表單輸入綁定

這篇是 資料綁定(data-binding) 的補充,將我們常用的輸入介面與Vue的資料綁在一起。

若是漏了前面章節,可以回去翻翻

常用的表單元素有

  • 文字輸入欄
<input type="text" v-model="message" placeholder="edit here">
{{ message }}
<textarea v-model="note" placeholder="edit here"></textarea>
{{ message }}
  • 下拉選單
<select v-model="selected">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
<span>Selected: {{ selected }}</span>
  • 單選
<input type="radio" id="developer" value="developer v-model="role">
<label for="developer">{{ developer }}</label>
<input type="radio" id="manager" value="manager" v-model="role">
<label for="manager">{{ manager }}</label>
<input type="radio" id="designer" value="designer" v-model="role">
<label for="designer">{{ designer }}</label>

<span>職稱: {{ role }}</span>```

- 多選

沒指定時,對應 `checked` 屬性的 `true/false`

有指定 value 時,選取時會取得 字串,例如 'gaming'

<input type="checkbox" id="gaming" value="gaming" v-model="habits">
<label for="gaming">{{ gaming }}</label>
<input type="checkbox" id="coding" value="coding" v-model="habits">
<label for="coding">{{ coding }}</label>
<input type="checkbox" id="hiking" value="hiking" v-model="habits">
<label for="hiking">{{ hiking }}</label>

<span>興趣: {{ habits }}</span>

有時你想要數值,而不是字串。
有時你想要防止使用者用空白充數。
有時你想要使用者打完字才更新資料。

就像事件處理給你方便,v-model也給你方便修飾子,

<input text="number" v-model.number>
<input text="text" v-model.trim>
<input text="text" v-model.lazy>

有時不選,也是一種選擇,只是跟預設答案不同。
有時候題目一樣,但答案應狀況而定,不是定值。

綁定特定屬性 v-bind:attr,能小巧而靈活地克服這些問題

	data: {
		isMoeMoe: false, /* 萌萌嗎 */
		a: 'Yes'
	},
	computed: {
		b: function() {
			return (isMoeMoe) ? 'Yes' : 'No';
		}
	}
萌萌嗎?<input type="checkbox" v-model="isMoeMoe">
<p>只要雙方同意,就讓他們在一起吧</p>
<input
  type="checkbox"
  v-model="toggle"
  v-bind:true-value="a"
  v-bind:false-value="b">

搭配陣列更是威力百倍

	data: {
		swords: [
			'老媽的鹹魚',
			'尚方寶劍',
			'清朝的刀'
		]
	}
<p>常威喜歡哪一把</p>
<select v-model="selected">
	<opttion>老大別砍我</option>
	<opttion v-for="sword in swords" :value="sword"></option>
</select>

	data: {
		options: ['gaming', 'coding', 'hiking', 'alwayEat', 'alwaysSleep']
	}
<template v-for="habit in options">
<input type="checkbox"
       id="{{ habit }}"
       :value="habit"
       v-model="habits">
<label for="{{ habit }}">{{ habit }}</label>
</template>

<span>興趣: {{ habits }}</span>


還算容易吧?
往後將會談到進階的綜合應用,等我們介紹完Component,就來處理來自客戶/設計師/老闆的的特別需求 - 自製表單元件。


上一篇
Vue.js 11 - DOM事件處理
下一篇
Vue.js 13 - 組件/元件(Component) - 用途及使用方式
系列文
Vue.js 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
sunny
iT邦新手 5 級 ‧ 2020-08-12 00:12:07

小小修改一下
b是return(this.isMoeMoe)喔~

我要留言

立即登入留言