您好,登錄后才能下訂單哦!
怎么在vue中實現(xiàn)一個@change事件?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="vue.js"></script> <body> <div id="app"> <select name="" id="" @change="getCity(provinceId)" v-model="provinceId"> <option value="">請選擇</option> <option v-for="province in provinces" :value="province.id">{{province.text}}</option> </select> <select name="" id=""> <option value="">請選擇</option> <option :value="city.id" v-for="city in citys">{{city.text}}</option> </select> </div> </body> <script> new Vue({ el:'#app', data:{ provinces:[], provinceId:'', citys:[], areas:[] }, created:function() { this.areas = [ {text:'廣東省',id:1,pid:0}, {text:'上海市',id:2,pid:0}, {text:'廣州市',id:11,pid:1}, {text:'中山市',id:12,pid:1} ]; var provinces=this.areas.filter(function (area) { return area.pid == 0; }); this.provinces = provinces; }, methods:{ getCity:function (id) { var citys=this.areas.filter(function (city) { return city.pid == id; }) this.citys = citys; } } }) </script> </html>
如果按照平常的使用習(xí)慣,看起來好像沒多大問題,切換父元素的時候監(jiān)聽change事件聯(lián)動子元素值的變化,很符合常年使用jQuery開發(fā)的習(xí)慣,效果如圖:
那如果頁面上有多個使用到相同的聯(lián)動效果的地方呢?我們看下效果會是怎樣,如圖
<select name="" id="" @change="getCity(provinceId)" v-model="provinceId"> <option value="">請選擇</option> <option v-for="province in provinces" :value="province.id">{{province.text}}</option> </select> <select name="" id=""> <option value="">請選擇</option> <option :value="city.id" v-for="city in citys">{{city.text}}</option> </select> <select name="" id="" @change="getCity(provinceId)" v-model="provinceId"> <option value="">請選擇</option> <option v-for="province in provinces" :value="province.id">{{province.text}}</option> </select> <select name="" id=""> <option value="">請選擇</option> <option :value="city.id" v-for="city in citys">{{city.text}}</option> </select>
結(jié)果是互相受到影響,這并不是我們想看到的。
我的解決辦法是,citys改為一個實時計算得到的數(shù)組而不是綁定現(xiàn)有僅有的同一個數(shù)組,代碼改寫如下:
<select name="" id=""> <option value="">請選擇</option> <option :value="city.id" v-for="city in getCity(provinceId)">{{city.text}}</option> </select> getCity:function (id) { var citys=this.areas.filter(function (city) { return city.pid == id; }) return citys; }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。