Form Binding Vue 3.0.0
表單綁定 Vue 3.0.0
by Chris_Walter
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.2/axios.min.js"></script>
<div id="app">
<form>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" v-model="email">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" v-model="password">
</div>
<div class="mb-3">
<select v-model="citySelected" class="form-select" aria-label="Default select example">
<option selected disabled value="">請選擇城市</option>
<option v-for="item in city.name" :key="item.uid" :value="item.city">{{item.city}}</option>
</select>
</div>
<div class="mb-3">
<select v-model="communitySelected" class="form-select" aria-label="Default select example">
<option selected disabled value="">請選擇社區</option>
<option v-for="item in city.community" :key="item.uid">{{ item.community }}</option>
</select>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" v-model="check">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary" @click="handSubmit">Submit</button><span>未輸入的欄位:</span>
</form>
</div>
JavaScript
const { ref, reactive, createApp, onMounted, watch } = Vue;
const vm = {
setup(){
const email = ref('');
const password = ref('');
const check = ref(false);
const validate = () => {
if(email.value === '' || password.value === ''){//也可使用length判斷字串是否為空
return false;
}
return true;
}
const handSubmit = () => {
if(validate()){
console.log(email.value, password.value, check.value);
alert('表單已送出');
} else {
alert('還有欄位未填');
}
}
const city = reactive({ name: [], community: [] });
const citySelected = ref('');
const communitySelected = ref('');
onMounted(() => {
axios.get('https://random-data-api.com/api/address/random_address?size=30').then((res) => {
console.log(res.data);
city.name = res.data;
})
});
watch([citySelected, communitySelected], ([newCity, newCommunity]) => {
const currentCityCommunity = city.name.filter((el) => el.city === newCity);
console.log(newCity, newCommunity);
city.community = currentCityCommunity;
});
return{
email,
password,
check,
handSubmit,
city,
citySelected,
communitySelected
}
}
};
createApp(vm).mount('#app');