Vue.extend挂载到实例上

2020-04-02 08:44:01

主要是做个笔记


根据官网的说法,Vue.extend:是使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。


官网的用法是:

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

1

2

3

4

5

6

7

8

9

10

11

12

13

最终结果如下:

<p>Walter White aka Heisenberg</p>


感觉这样写不太美观


于是改为下面这样写:

在文件夹./src/component/expend,新建两个文件:main.js和main.vue

main.vue就是你的组件,爱怎么写怎么写

main.js是把组件挂载到实例上,代码如下:


import Vue from 'Vue'

import Main from './main.vue'

let Builder = Vue.extend(Main)

export default {

install (vue) {

vue.prototype.$YOURNAME = this.getComponent

},

getComponent (param) {

let instance = new Builder({

propsData: { param }

})

instance.vm = instance.$mount()

document.body.appendChild(instance.vm.$el)

return instance

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

在入口文件main.js,添加代码:


import Vue from 'Vue'

import myComponent from './src/component/expend/main.js'

Vue.use(myComponent)

1

2

3

然后在页面中就可以这样使用了:


this.$YOURNAME(param)


  • 2020-02-19 23:04:52

    理解Laravel中的pipeline

    pipeline在laravel的启动过程中出现次数很多,要了解laravel的启动过程和生命周期,理解pipeline就是其中的一个关键点。网上对pipeline的讲解很少,所以我自己写一写吧。

  • 2020-02-19 23:08:56

    Laravel 用户认证 Auth(精华)

    很多应用是需要登陆后才能操作,Laravel 提供了一个 auth 工具来实现用户的认证功能。并且有一个 config/auth.php 来配置 auth 工具。大概看一下 auth 工具的常用方法

  • 2020-02-19 23:12:44

    Laravel 从 $request 到 $response 的过程解析二(必读)

    laravel 的请求会组装成 $request 对象,然后会依次经过中间件(前置部分),最终到达 url 指向的控制器方法,然后把返回数据组装为 $response 对象返回,再依次经过中间件 (后置部分),最终返回。

  • 2020-02-19 23:15:24

    PHP 闭包(Closure)

    闭包(Closure)又叫做匿名函数,也就是没有定义名字的函数。比如下面的例子: