Vue.extend
属于 Vue 的全局 API,在实际业务开发中咱们不多使用,由于相比经常使用的 Vue.component
写法使用 extend
步骤要更加繁琐一些。可是在一些独立组件开发场景中,Vue.extend
+ $mount
这对组合是咱们须要去关注的。html
学习开始以前咱们先来看一下官方文档是怎么描述的。vue
参数:api
{Object} options
用法:app
使用基础 Vue 构造器,建立一个“子类”。参数是一个包含组件选项的对象。ide
data
选项是特例,须要注意 - 在 Vue.extend()
中它必须是函数函数
<div id="mount-point"></div>
// 建立构造器 var Profile = Vue.extend({ template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White', alias: 'Heisenberg' } } }) // 建立 Profile 实例,并挂载到一个元素上。 new Profile().$mount('#mount-point')
结果以下:学习
<p>Walter White aka Heisenberg</p>
参考:组件ui
能够看到,extend
建立的是 Vue 构造器,而不是咱们平时常写的组件实例,因此不能够经过 new Vue({ components: testExtend })
来直接使用,须要经过 new Profile().$mount('#mount-point')
来挂载到指定的元素上。code
在 vue 项目中,咱们有了初始化的根实例后,全部页面基本上都是经过 router 来管理,组件也是经过 import
来进行局部注册,因此组件的建立咱们不须要去关注,相比 extend
要更省心一点点。可是这样作会有几个缺点:component
#app
下渲染,注册组件都是在当前位置渲染。若是我要实现一个相似于 window.alert()
提示组件要求像调用 JS 函数同样调用它,该怎么办?这时候,Vue.extend + vm.$mount
组合就派上用场了。
咱们照着官方文档来建立一个示例:
import Vue from 'vue' const testComponent = Vue.extend({ template: '<div>{{ text }}</div>', data: function () { return { text: 'extend test' } } })
而后咱们将它手动渲染:
const extendComponent = new testComponent().$mount()
这时候,咱们就将组件渲染挂载到 body
节点上了。
咱们能够经过 $el
属性来访问 extendComponent
组件实例:
document.body.appendChild(extendComponent.$el)
若是想深刻掌握 extend 知识,不妨作一个 alert 组件来实现相似于原生的全局调用。
加油!