天天看点

Vue之深入理解extend与手动挂载$mount

上一章节我们说到,创建一个vue实例的时候,都会有一个选项el,来指定实例的根节点,如果不写el选项,那组件就处于未挂载状态。​

​Vue.extend​

​​ 的作用,就是基于 Vue 构造器,创建一个“子类”,它的参数跟 ​

​new Vue​

​​ 的基本一样,但 ​

​data​

​​ 要跟组件一样,是个函数,再配合 ​

​$mount​

​ ,就可以让组件渲染,并且挂载到任意指定的节点上,比如 body。
import Vue from 'vue';

const AlertComponent = Vue.extend({
  template: '<div>{{ message }}</div>',
  data () {
    return {
      message: 'Hello, Aresn'
    };
  },
});      

这一步,我们创建了一个构造器,这个过程就可以解决异步获取 template 模板的问题,下面要手动渲染组件,并把它挂载到 body 下:

const component = new AlertComponent().$mount();      

这一步,我们调用了 ​

​$mount​

​​ 方法对组件进行了手动渲染,但它仅仅是被渲染好了,并没有挂载到节点上,也就显示不了组件。此时的 ​

​component​

​​ 已经是一个标准的 Vue 组件实例,因此它的 ​

​$el​

​ 属性也可以被访问:

document.body.appendChild(component.$el);      

当然,除了 body,你还可以挂载到其它节点上。

​$mount​

​ 也有一些快捷的挂载方式,以下两种都是可以的:

// 在 $mount 里写参数来指定挂载的节点
new AlertComponent().$mount('#app');
// 不用 $mount,直接在创建实例时指定 el 选项
new AlertComponent({ el: '#app' });      

实现同样的效果,除了用 extend 外,也可以直接创建 Vue 实例,并且用一个 Render 函数来渲染一个 .vue 文件:

import Vue from 'vue';
import Notification from './notification.vue';

const props = {};  // 这里可以传入一些组件的 props 选项

const Instance = new Vue({
  render (h) {
    return h(Notification, {
      props: props
    });
  }
});

const component = Instance.$mount();
document.body.appendChild(component.$el);      
const notification = Instance.$children[0];      

继续阅读