Stateful Vue Plugins
Example
- Create a v-edit directive that enables contenteditable for a given HTML element
- Globally enable/disable contenteditable (e.g. edit vs. read-only modes)
Example
- Create a <editable-component> component that decorates it's content with more DOM
- Globally enable/disable the wrapper (e.g. edit vs. read-only modes)
Why have a stateful plugin?
- Allow global/external control of state that might not be appropriate to track in individual components or Vuex
- Allow mixins and directives to change component behavior
- Alternative to install(Vue, options), i.e. Vue.use(PluginInstance, <options go here>)
Jason San Jose
Senior Computer Scientist, Adobe
Twitter: @jasonsanjose
Github: @jasonsanjose
Slides
http://slides.com/jasonsanjose/vueconf2017
Backup Slides
Title Text
const EditPlugin = new Vue({
data() {
return { enableEdit: false }
},
watch: {
enableEdit() {
// "re-render" all elements when enableEdit changes
this.renderAll();
}
},
methods: {
render(el) {
el.setAttribute('contenteditable', this.enableEdit);
},
renderAll() {
this._elements.forEach((el) => this.render(el));
},
install(Vue) {
this._elements = new Set();
Vue.directive('edit', {
bind(el) {
EditPlugin._elements.add(el);
// "render" the directive for the current element
EditPlugin.render(el);
},
unbind(el) {
EditPlugin._elements.remove(el);
}
});
}
}
});
Title Text
Vue.use(EditPlugin);
new Vue({
el: '#app',
computed: {
enableEdit() {
return EditPlugin.enableEdit;
},
buttonLabel() {
return this.enableEdit ? 'Save' : 'Edit';
}
},
methods: {
toggleEdit() {
// Update plugin state
EditPlugin.enableEdit = !EditPlugin.enableEdit;
}
},
template: `
<div>
<button @click="toggleEdit">{{ buttonLabel }}</button>
<h1 v-edit>Heading</h1>
<p v-edit>Paragraph</p>
</div>`
});
Stateful Vue Plugins
By Jason San Jose
Stateful Vue Plugins
Advanced Vue plugin example that goes beyond initialization options.
- 836