Level: beginner • Mithril.js Version: latest
component key m.mount oninit vnode
To distinguish similar vnodes from eachother, use the KEY attribute (keyword), and give it a unique value. Keep in mind that all siblings must be keyed for it to work. See also the Mithril.js docs. This can be used to force a component to re-instantiate/re-initialize. In this example 2 comp instances are created, but only the 'foo' one gets a changeable key, ensuring the re-init when the key changes.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
const comp = {
oninit: vnode => console.log('init ' + vnode.attrs.name),
view: vnode => m('div', vnode.attrs.name + ' key: ' + vnode.attrs.key)
}
const app = () => {
count = 0
return {
oninit: () => {console.log('init app')},
view: () => [
m('div', 'Test',
['foo','bar'].map(x => m(comp, {name: x, key: x === 'foo' && count}))
),
m('button', {onclick: () => count++}, 'click')
]
}
}
m.mount(document.body, app)
As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.
In this code sample Mithril.js' m.mount
API method is use, besides the basic hyperscript function m().
Moreover, it shows how the lifecycle method oninit
can be used (better known as hook).
Also covered in this example is the use of Vnodes or virtual DOM nodes, a JavaScript data structure that describes a DOM tree.
The example was written by osban, last edits were made on 24 September 2020. The author has contributed some more snippets. Click here to see them all.
Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!