若我們欲使表單輸入框同步給變數值,會使用 v-bind
綁定,再使用 v-on
監聽事件
<input
:value="text"
@input="event => text = event.target.value">
而 Vue 提供了更方便的寫法,那就是 v-model
<template>
<div class="box">
<input v-model="message" />
<textarea v-model="message"></textarea>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('v-model 讚讚!')
</script>
<style scoped>
.box{
gap:5px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
font-size: x-large;
border: solid;
margin-left: 650px;
margin-top: 5px;
height: 200px;
width:350px;
padding: 35px;
}
</style>
textarea
內的文字可以隨著 input
變動
這邊我犯了低級錯誤,忘了寫這一行事先定義 message
,所以 v-model
不知道要綁定誰
const message = ref('...')
用在 checkbox
<template>
<div class="box">
<div>
<label>a</label><input type="checkbox" value="a" v-model="checked"></input>
</div>
<div>
<label>b</label><input type="checkbox" value="b" v-model="checked"></input>
</div>
<div>
<label>c</label><input type="checkbox" value="c" v-model="checked"></input>
</div>
<p>checkbox: {{ checked }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const checked = ref([])
</script>
<style scoped>
.box{
/* gap: 20px; */
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
font-size: x-large;
border: solid;
margin-left: 650px;
margin-top: 5px;
height: 200px;
width:350px;
padding: 35px;
}
</style>
用一個 checked 陣列紀錄勾選了哪些 checkbox
用在 ratio
<template>
<div class="box">
<div>
<input type="radio" value="A" v-model="picked"> A </input>
<input type="radio" value="B" v-model="picked"> B </input>
</div>
<p>picked: {{ picked }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const picked = ref('')
</script>
預設單選鈕所以只會顯示 A
或是 B
用在 select 下拉式選單
<template>
<div class="box">
<select v-model="selected">
<option value="apple">蘋果</option>
<option value="banana">香蕉</option>
<option value="grape">葡萄</option>
</select>
<p>selected: {{ selected }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const selected = ref('')
</script>
ref:
https://zh-hk.vuejs.org/guide/essentials/forms.html
https://ithelp.ithome.com.tw/m/articles/10239723