Form Binding Vue 2.6.12

表單綁定 Vue 2.6.12

by Chris_Walter

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.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" :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 currentCityCommunity"  :key="item.uid" :value="item.community">{{ 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>
</form>
</div>

JavaScript

const vm = new Vue({
  data() {
    return {
      email: '',
      password: '',
      check: false,
			city: [],
			currentCityCommunity: [],
			citySelected: '',
			communitySelected: ''
    }
  },
  methods: {
	  validate() {
		  if(this.email === '' || this.password === ''){
			  return false;
			}
			return true;
		},
    handSubmit() {
		  if(this.validate()){
				console.log(this.email, this.password, this.check);
				alert('表單已送出');
			} else {
			  alert('還有欄位未填');
			}
    },
		getCityData() {
		  axios.get('https://random-data-api.com/api/address/random_address?size=30').then((res) => {
			  this.city = res.data;
			});
		}
  },
	created(){
	  this.getCityData();
	},
	watch: {
	  citySelected(newCity){
		  console.log(newCity);
		  const community = this.city.filter((el) => el.city === newCity);
			this.currentCityCommunity = community;
		},
		communitySelected(newCommunity){
		  console.log(newCommunity);
		}
	}
});

vm.$mount('#app');