vue.extend学习

作用:使用基础 Vue 构造器,创建一个“子类”。
参数是一个包含组件选项的对象。

原理:1.使用vue.extend创造构造器Profile
2. 将构造器实例化并且将创建的新vue实例挂载到元素上
new Profile().$mount('#mount-point')

官网上

<template>
<div id="mount-point"></div>
</template>

<script>
import Vue from 'vue'

var Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',//发现Id为mount-point的div ,是直接被template的p元素替代了,dom中没有Id为mount-point的div

> template标签,更加规范和语义化。可以把列表项放入template标签中,然后进行批量渲染

  data: function () {
    return {
      firstName: 'Walter',
      lastName: 'White',
      alias: 'Heisenberg'
    }
  }
})
new Profile().$mount('#mount-point')

运行的时候会报错
在这里插入图片描述
不理解为什么会找不到,百度搜索了一下,有可能是没有绑定节点
然后加了一段代码document.getElementById('mount-point').$mount(Profile.$el)
还是不行,报错为 Cannot read properties of null (reading ‘appendChild’)
有可能是
你获取这节点时,节点还没加载或者你获取的节点不存在引起的。

解决:直接在template里写

<template>
</template>

<script>

import Vue from 'vue'

const testComponent = Vue.extend({
  template: '<div>{{ text }}</div>',
  data: function () {
    return {
      text: 'extend '
    }
  }
})
const extendComponent = new testComponent().$mount()//手动渲染(名称不能相同)
document.body.appendChild(extendComponent.$el)//通过$el属性来访问extendComponent组件实例
export default {

}
</script>

<style>

</style>

结果显示 Walter White aka Heisenberg

问题:为什么我绑定id时用不了。
解决:因为mounted比created先执行,页面还没有渲染,所以找不到‘mount-point’

<template>
<div id="mount-point"></div>
</template>

<script>
import Vue from 'vue'

const Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  data: function () {
    return {
      firstName: 'Walter',
      lastName: 'White',
      alias: 'Heisenberg'
    }
  },
 
})

export default {
    created(){
        Profile

    },
     mounted() {
      new Profile().$mount('#mount-point')
  }

}
</script>

<style>

</style>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值