作用:使用基础 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>