功能描述:
通過點擊按鈕,可以增減購物數量
組件名稱是 CouterBtn
最終效果如下

我們使用 vue-cli搭建基本的開發環境,這也是最快的進行 .vue組件開發的方式
對于入口組件 App.vue (可以暫時忽略其他細節,我們的重點是如何寫組件)
App.vue
<template> <div id="app"> <h4>這是一個利用 v-model實現的自定義的表單組件</h4> <h6>CouterBtn組件的值 <i> {{ btnValue }} </i></h6> 5. <counter-btn v-model="btnValue"></counter-btn> <form class="" action="/add" method="post"> <!-- 真實情況請將 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"> h6 i border 1px dotted form30. margin-top 20px padding 20px border 1px dotted #ccc label vertical-align: middle35. </style>下面我來對 App.vue中的一些代碼進行一些說明,根據代碼行數來說明
4 : 我們使用 {{ btnValue }}來獲取自定義組件 counter-btn的值, 這里僅僅是展示效果用
5: 我們使用了counter-btn ,自定義的組件
9: 我們將自定義組件的值,綁定到我們的表單組件 input中去, 在真實的情況下, 此 input的類型可能為 hidden類型
21: 由于我們需要在App.vue組件中使用我們自定義的組件 counter-btn,所以需要使用 components注冊組件, 這里還使用了 ES6的對象解構
26: 我們使用CSS預處理器為stylus, 前提是你的 node_modules中要安裝此npm包和loader,vue-cli已經幫我們處理好了stylus的編譯; 根據個人情況選擇
我們自己設計的組件通過 v-model,把組件內部的值傳給了它所綁定的值
下面我們來看看我們的組件的實現
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 030. outline 0 border-radius 3px button:nth-child(2) width 200px </style>我們可以看到組件的實現非常簡單, 3個button搞定; 這里最關鍵的代碼是
this.$emit('input', {res: this.result, other: '++'})
通過 觸發 input事件和自定的數據來實現把數據暴露給 v-model綁定的屬性值
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網
新聞熱點
疑難解答