簡書原文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測試