Vue.js input swapping example
A Vue.js tutorial for having text fields convert to inputs when clicked
by James Doyle
HTML
<div id="app">
<p v-input-swap>A Field With Text 1</p>
<p v-input-swap>A Field With Text 2</p>
<p v-input-swap>A Field With Text 3</p>
<p v-input-swap>A Field With Text 4</p>
<p v-input-swap>A Field With Text 5</p>
</div>
CSS
body {
padding: 2em;
}
p, .form-control {
font-size: 1em;
margin-bottom: 1em;
}
JavaScript
Vue.directive('input-swap', {
bind: function() {
var self = this;
self.handleClick = function(event) {
var val = this.innerText;
var parent = this.parentElement;
this.setAttribute('data-swap', 'input-swap');
var oldel = this.outerHTML;
var newel = this.outerHTML = "<input id=\"input-swap\" class=\"form-control\" type=\"text\" value=\"" + val + "\" >";
var input = parent.querySelector('#input-swap');
input.select();
input.addEventListener('blur', function() {
this.outerHTML = oldel.replace(val, this.value);
var newnewel = parent.querySelector('[data-swap="input-swap"]');
newnewel.removeAttribute('data-swap');
newnewel.addEventListener('click', self.handleClick);
});
};
this.el.addEventListener('click', self.handleClick);
},
update: function(value) {
// $(this.el).val(value).trigger('input');
},
unbind: function() {
this.el.removeEventListener('click', this.handleClick);
}
});
var App = new Vue({
el: '#app'
});