Last active
October 15, 2017 11:50
-
-
Save yyx990803/fa9b369661ab04c87af1 to your computer and use it in GitHub Desktop.
Vue custom element draft
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Vue.js custom element example</title> | |
<script src="../dist/vue.js"></script> | |
</head> | |
<body> | |
<my-element msg="custom message">original content</my-element> | |
<script> | |
Vue.element = function (tag, options) { | |
var p = Object.create(HTMLElement.prototype) | |
// Handle attached/detached callbacks | |
p.attachedCallback = options.attached | |
p.detachedCallback = options.detached | |
// disable Vue's own attached/detached detection | |
// so we don't fire the callback twice | |
options.attached = null | |
options.detached = null | |
// Handle param attributes | |
var params = options.paramAttributes || [] | |
var paramsHash = Object.create(null) | |
params.forEach(function (name) { | |
paramsHash[name] = true | |
Object.defineProperty(p, name, { | |
get: function () { | |
return this.__vue__[name] | |
}, | |
set: function (val) { | |
this.setAttribute(name, val) | |
} | |
}) | |
}) | |
p.attributeChangedCallback = function (name, oldVal, newVal) { | |
if (paramsHash[name]) { | |
this.__vue__[name] = newVal | |
} | |
} | |
// Define the Vue constructor to manage the element | |
var VM = Vue.extend(options) | |
p.createdCallback = function () { | |
new VM({ el: this }) | |
} | |
document.registerElement(tag, { | |
prototype: p | |
}) | |
} | |
/** | |
* Usage example, exactly the same with Vue.component, | |
* except it's a real custom element (in supported browsers) | |
*/ | |
Vue.element('my-element', { | |
template: | |
'<h1>This is a Vue custom element!</h1>' + | |
'<h2>{{msg}}</h2>' + | |
'<content></content>', | |
paramAttributes: ['msg'], | |
data: function () { | |
return { | |
msg: 'default message' | |
} | |
}, | |
attached: function () { | |
console.log('attached!') | |
}, | |
detached: function () { | |
console.log('detached!') | |
} | |
}) | |
var el = document.querySelector('my-element') | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment