简书原文css
作东西一贯奉行的是致简原则,必定要让使用者简单
这是我在使用 Vue 一段时间后尝试制做的一个小玩意
我但愿能够作一堆这样的小玩意,随意组合使用,感受挺好的
源码在最后html
演示DEMOvue
<input type="checkbox" id="test1"/>
var test1 = new vCheckBox({ el: "#test1", data: { text: "测试多选框" } });
图片使用base64方式写入css,css写入行内样式
使用template
变量保存默认模版,在extend中{ template: template }
,而后再赋值给全局对象 vCheckBox.template1 = template;
之后能够预制更多不一样样式的 template, 在使用中只须要 new vCheckBox( { template : vCheckBox.templateN } )
一样的,若是不想使用任何样式也能够 new vCheckBox( { template : null } )
git
(function (window) { if (window == null || window.Vue == null) { return; } var version = "1.1.0.0"; var template = '<div style="......" ....>\ <ins :style="....." style="...background-image: url(data:image/png;base64,iVBORw0KGgoAA......gg==);..."></ins>\ <span style="display: inline-block;*display: inline;*zoom: 1;vertical-align: middle;">{{text}}</span>\ <slot></slot>\ </div>'; var vue = window.Vue; var vCheckBox = vue.extend({ ... ... template: template }; vCheckBox.template1 = template; vCheckBox.version = version; window.vCheckBox = vCheckBox; })(window);
当vCheckbox作为子组件使用时,props: ["checked", "text", "disabled"]
三个属性能够由父组件传入;
因为Vue自己的限制,当属于由props传入时则没法被赋值(会变为只读),这个限制能够参考官方文档
因此在data部分须要对prop进行判断github
data: function () { var props = this.$options.propsData; var data = { _hover: 0, _readonly: { text: props && props.hasOwnProperty("text"), disabled: props && props.hasOwnProperty("disabled"), checked: props && props.hasOwnProperty("checked") } }; if (!data._readonly.text) { data.text = ""; } if (!data._readonly.disabled) { data.disabled = false; } if (!data._readonly.checked) { data.checked = false; } return data; }
在toggle操做的时也须要注意ide
methods: { toggle: function () { if (this.disabled) { return; } var value = this.checked == null ? false : !this.checked; if (this.$data._readonly.checked) { this.onChanged(value); return; } this.checked = value; },
为了方便在使用时操做全选和判断全选
写了2个独立的函数供调用,能够在判断时指定须要判断的字段的名称field
参数,默认为判断对象的checked
字段
另外checked
状态还提供了额外的半选状态
(常见于全选的部分选中,另一部分未选中)
半选状态返回null
,不影响true和false的判断 null在if中也会被认为是false,兼容只有2个状态的状况函数
vCheckBox.checkAll = function (value, objects, field) { if (typeof value !== "boolean" || objects == null) { return; } if (typeof field !== "string") { field = "checked"; } for (var key in objects) { if (objects.hasOwnProperty(key)) { var obj = objects[key]; if (obj && obj.hasOwnProperty(field) && obj[field] !== value) { obj[field] = value; } } } }; vCheckBox.isCheckAll = function (objects, field) { if (objects == null) { return false; } if (typeof field !== "string") { field = "checked"; } var value = null; for (var key in objects) { if (objects.hasOwnProperty(key)) { var obj = objects[key]; if (obj && obj.hasOwnProperty(field)) { if (value == null) { value = obj[field]; } else if (value !== obj[field]) { return null; } } } } return value; };
github测试