您好,登錄后才能下訂單哦!
這篇文章主要介紹怎么利用Vue v-model實(shí)現(xiàn)一個(gè)自定義的表單組件,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以創(chuàng)建可維護(hù)性和可測(cè)試性更強(qiáng)的代碼庫(kù),Vue允許可以將一個(gè)網(wǎng)頁(yè)分割成可復(fù)用的組件,每個(gè)組件都包含屬于自己的HTML、CSS、JavaScript,以用來(lái)渲染網(wǎng)頁(yè)中相應(yīng)的地方,所以越來(lái)越多的前端開(kāi)發(fā)者使用vue。
功能描述:
通過(guò)點(diǎn)擊按鈕,可以增減購(gòu)物數(shù)量
組件名稱(chēng)是 CouterBtn
最終效果如下
我們使用 vue-cli搭建基本的開(kāi)發(fā)環(huán)境,這也是最快的進(jìn)行 .vue組件開(kāi)發(fā)的方式
對(duì)于入口組件 App.vue (可以暫時(shí)忽略其他細(xì)節(jié),我們的重點(diǎn)是如何寫(xiě)組件)
App.vue
<template> <div id="app"> <h5>這是一個(gè)利用 v-model實(shí)現(xiàn)的自定義的表單組件</h5> <h7>CouterBtn組件的值 <i> {{ btnValue }} </i></h7> 5. <counter-btn v-model="btnValue"></counter-btn> <form class="" action="/add" method="post"> <!-- 真實(shí)情況請(qǐng)將 type改為hidden --> <label for="count">值綁定到 input 隱藏域里</label> <input type="text" name="count" :value="btnValue.res" id="count"> 10. </form> </div> </template> <script> import CounterBtn from './components/CouterBtn.vue' 15. export default { data() { return { btnValue: {} } 20. }, components: { CounterBtn } } 25. </script> <style lang="stylus"> h7 i border 1px dotted form 30. margin-top 20px padding 20px border 1px dotted #ccc label vertical-align: middle 35. </style>
下面我來(lái)對(duì) App.vue中的一些代碼進(jìn)行一些說(shuō)明,根據(jù)代碼行數(shù)來(lái)說(shuō)明
4 : 我們使用 {{ btnValue }}來(lái)獲取自定義組件 counter-btn的值, 這里僅僅是展示效果用
5: 我們使用了counter-btn ,自定義的組件
9: 我們將自定義組件的值,綁定到我們的表單組件 input中去, 在真實(shí)的情況下, 此 input的類(lèi)型可能為 hidden類(lèi)型
21: 由于我們需要在App.vue組件中使用我們自定義的組件 counter-btn,所以需要使用 components注冊(cè)組件, 這里還使用了 ES6的對(duì)象解構(gòu)
26: 我們使用CSS預(yù)處理器為stylus, 前提是你的 node_modules中要安裝此npm包和loader,vue-cli已經(jīng)幫我們處理好了stylus的編譯; 根據(jù)個(gè)人情況選擇
我們自己設(shè)計(jì)的組件通過(guò) v-model,把組件內(nèi)部的值傳給了它所綁定的值
下面我們來(lái)看看我們的組件的實(shí)現(xiàn)
CounterBtn.vue
<template> <div class="coutter-wrapper"> <button type="button" @click="plus">+</button> <button type="button">{{ result }}</button> 5. <button type="button" @click="minus">-</button> </div> </template> <script> export default { 10. methods: { minus() { this.result--; this.$emit('input', {res: this.result, other: '--'}) }, 15. plus() { this.result++; this.$emit('input', {res: this.result, other: '++'}) } }, 20. data() { return { result: 0, } } 25. } </script> <style lang="stylus" scoped> button border 0 30. outline 0 border-radius 3px button:nth-child(2) width 200px </style>
我們可以看到組件的實(shí)現(xiàn)非常簡(jiǎn)單, 3個(gè)button搞定; 這里最關(guān)鍵的代碼是
this.$emit('input', {res: this.result, other: '++'})
通過(guò) 觸發(fā) input事件和自定的數(shù)據(jù)來(lái)實(shí)現(xiàn)把數(shù)據(jù)暴露給 v-model綁定的屬性值
以上是“怎么利用Vue v-model實(shí)現(xiàn)一個(gè)自定義的表單組件”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。