>[success] # 封装一个checkbox [这个章节文章参考](https://juejin.im/book/5bc844166fb9a05cd676ebca/section/5bdc0e596fb9a049d7471ddb) >[danger] ##### 需要知道的知识点 ~~~ 1.一个组件最重要的三个组成部分依次是'prop','event','solt' 2.要知道 input  的 v-model 语法糖是'input' 和 'value' 缩写 3.要知道并不是所有公司的'checkbox' 绑定的都是true 和 false ~~~ >[danger] ##### 看一下iview -- checkbox组件 ~~~ <template> <i-checkbox v-model="single">单独选项</i-checkbox> </template> <script> export default { data () { return { single: false } } } </script> ~~~ >[danger] ##### 封装一个 ~~~ 1.为了可以在使用组件的时候可以直接绑定'v-model',所以需要预留'value' 和 '$emit("input")' 2.组件的最外层是'input'原生,因此使用v-model,相当于组件prop字段默认有了一个'value' 3.这里有个注意点'<input>、<slot>' 都是包裹在一个 '<label>' 元素内的,这样做的好处是,当点击 '<slot>' 里的文字 时,'<input>' 选框也会被触发,否则只有点击那个小框才会触发,那样不太容易选中,影响用户体验。 4.创建目录可以参考如图: ~~~ ![](https://img.kancloud.cn/7d/8e/7d8ebc45e92591aa92aa38eb9a7f8ae5_342x155.png) ~~~ <template> <label> <span> <input type='checkbox' :disabled='disabled' :checked='currentValue' @change="change"> <slot></slot> </span> </label> </template> <script> export default { name: 'iCheckbox', props: { disabled: { type: Boolean, default: false, }, value: { type: [String, Number, Boolean], default: false }, trueValue: { type: [String, Number, Boolean], default: true }, falseValue: { type: [String, Number, Boolean], default: false } }, data () { return { currentValue: this.value } }, methods: { change (event) { // 如果 禁选 那么下面的逻辑都不执行 if (this.disabled) { return false } const checked = event.target.checked this.currentValue = checked const value = checked ? this.trueValue : this.falseValue; this.$emit('input', value); this.$emit('on-change', value); }, // 这里是为了 应对特殊选中变量的定义,有时候不能保证 所有项目都是用true false 来控制 updateModel () { this.currentValue = this.value === this.trueValue; } }, watch: { value (val) { if (val === this.trueValue || val === this.falseValue) { this.updateModel(); } else { throw 'Value should be trueValue or falseValue.'; } } }, } </script> <style> </style> ~~~ >[danger] ##### 使用 ~~~ <template> <div> {{msg}} <CheckBox name='w' v-model="msg">足球</CheckBox> </div> </template> <script> import CheckBox from '@/components/checkbox' export default { components: { CheckBox }, data () { return { msg: true } }, methods: { } } </script> <style> </style> ~~~