我們創建Vue實例時,都會有一個el選項,來指定實例的根節點,如果不寫el選項,那組件就處於未掛載狀態。Vue.extend 的作用,就是基於 Vue 構造器,創建一個‘ 子類 ’,它的參數跟new Vue的基本一樣,但data要跟組件一樣,是個函數,再配合$mount,就可以渲染組件,並且掛載到任意指定的節點上,比如body(這是單文件組件做不到的)
下面我們就來看兩個例子:
1.在單文件組件中使用
<template>
<div id="about"></div>
</template>
<script>
import Vue from 'vue/dist/vue.js'
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// 創建 Profile 實例,並掛載到一個元素上。
let profile=new Profile().$mount();
export default {
mounted(){
let divid=document.getElementById('about');
divid.appendChild(profile.$el)
}
}
</script>
這裏需要注意幾個點:
- 報錯信息
如果有小夥伴遇到了這個問題,那麼你導入的是
import Vue from 'vue'
這個時候只需要修改成即可解決問題
import Vue from 'vue/dist/vue.js'
- 在單文件組件中的掛載問題:
因爲這裏是通過獲取節點的方式添加到某個元素內,所以一定要在鉤子函數中掛載,確保當前頁面的dom節點加載完成。
mounted(){
let divid=document.getElementById('about');
divid.appendChild(profile.$el)
}
2.單獨構建js文件
//index.js
import Vue from 'vue/dist/vue.js'
export default function Create(node){
var notiful=Vue.extend({
template:`<p>{{name}}</p>`,
data(){
return {
name:"liuhuas"
}
}
})
var noti=new notiful().$mount();
document.getElementById(node).appendChild(noti.$el);
}
創建完成後我們就可以在任何地方引入這個js文件 ,並執行Create方法,注意的是這裏的Create方法裏面也獲取了dom,那麼就需要在相應的鉤子函數中去執行這個方法。