vue全局api之extend

### 全局api之extend

vue.extend(函数)    注意:其中必须是函数
 这在我们实际的开发中使用的比较少,这是因为和我们常用的vue.component相比extend更加繁琐。

官网解释extend是vue的构造器,床架一个子类。参数是一个包含组件选项的对象

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')


我们在views中创建文件夹extend,其中有hello的js和vue

hello.vue

<!--hello.vue-->
<template>
  <div>{{text}}</div>
</template>
<script>
export default {
  name: 'hello',
  data () {
    return {
      text: ''
    }
  }
}
</script>

hello.js


/* jshint esversion: 6 */

import Vue from 'vue';
import HelloTemplate from '../extend/hello.vue';

// 使用extend方法创建vue的子类
const HelloConstructor = Vue.extend(HelloTemplate);

// 使用这个方法调用hello组件

function Hello(options) {
    options = options || {};
    if (typeof options === 'string') {
        options = {
            text: options
        };
    }

    // 实例化子组件,然后获取到DOM结构并挂载到body上
    const helloInstence = new HelloConstructor({ data: options });
    helloInstence.vm = helloInstence.$mount();
    console.log(helloInstence.vm)
    document.body.appendChild(helloInstence.vm.$el);
}
// 暴露接口
export default Hello;

在routerindex.js中导入hello.vue文件

import Hello from '../views/extend/hello.vue'
{
        path: '/',
        name: 'extend',
        component: Hello
        }

在main.js中

import Hello from './views/extend/hello';

Hello('hello world');


再宏伟的目标,拆分下来,也只是一串串的代码而已;一串串的代码,细分来看,也只是一个一个的字母而已!也许,我做不到一晚上完成大神一小时随便敲打的项目,但为这一目标,每天添砖加瓦,我想我应该是可以完成的!
原文地址:https://www.cnblogs.com/Annely/p/14641473.html