Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Last active October 15, 2017 11:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyx990803/fa9b369661ab04c87af1 to your computer and use it in GitHub Desktop.
Save yyx990803/fa9b369661ab04c87af1 to your computer and use it in GitHub Desktop.
Vue custom element draft
<!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