Home >Web Front-end >JS Tutorial >Vue life cycle, manual mounting and mounting subcomponents
This article mainly introduces the Vue life cycle and manual mounting to you. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
1. The life cycle of vue:
##2. $mount() manual mounting
Method one:
<p id="app"> {{name}} </p> <button onclick="test()">挂载</button> <script> var obj= {name: '张三'} var vm = new Vue({ data: obj }) function test() { vm.$mount("#app"); }
Method two:
Vue.extend() is used to create an unmounted subclass. You can use this subclass to create multiple instancesvar app= Vue.extend({ template: '<p>{{firstName}} {{lastName}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White' } } }) // 创建 app实例,并挂载到一个元素上。 new app().$mount('#app')Below we use automatic label insertion
Writing code by hand
1. First remove the display in user-name.vue Wrong label, because we have to manually insert<label class="label label-danger">用户不合法</label>2. First look at all the code of our plug-in validate.js, and then we analyze
export default{ install(Vue){ Vue.prototype.checkUserName = (value) => { if(value == ""){ return true; // 如果没有填写,默认为true } if(/\w{6,20}/.test(value)){ return true; }else{ return false; } } Vue.prototype.errorLabel = null; Vue.prototype.hasError = false; Vue.directive("uname",{ bind(){ let errorTpl = Vue.extend({ template:'<label class="label label-danger">用户不合法</label>' }); // 实例化并挂载 Vue.errorLabel = (new errorTpl()).$mount().$el; }, update(el,binding,vnode){ if(/\w{6,20}/.test(el.value)){ // 验证通过 if (Vue.hasError){ el.parentNode.removeChild(Vue.errorLabel); Vue.hasError = !Vue.hasError; } }else{ // 验证没有通过 if (!Vue.hasError){ el.parentNode.appendChild(Vue.errorLabel); Vue.hasError = ! Vue.hasError; } } }, }) } }3. Two prototypes are defined
Vue.prototype.errorLabel = null; Vue.prototype.hasError = false;errorLabel error prompt template, we create it in the bind() method and then mount it on it; hasError is an auxiliary attribute, which is convenient for us to judge whether there is an error or no error.
update(el,binding,vnode){ if(/\w{6,20}/.test(el.value)){ // 验证通过 if (Vue.hasError){ el.parentNode.removeChild(Vue.errorLabel); Vue.hasError = !Vue.hasError; } }else{ // 验证没有通过 if (!Vue.hasError){ el.parentNode.appendChild(Vue.errorLabel); Vue.hasError = ! Vue.hasError; } } },5. The demonstration effect is as shown below
The above is the detailed content of Vue life cycle, manual mounting and mounting subcomponents. For more information, please follow other related articles on the PHP Chinese website!