在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ vue 手動掛載$mount報錯? 學習element ui做一個自定義的動態(tài)組

vue 手動掛載$mount報錯? 學習element ui做一個自定義的動態(tài)組件

看了element ui的源碼想學習其思路做一個自定義的動態(tài)組件,具體操作如下:

創(chuàng)建一個main.vue文件:

<template>
    <div v-show="visible">{{message}}</div>
</template>

<script>
    export default{
        data(){
            return{
                message:'',
                visible:true
            }
        },
        methods:{
            close(){
                setTimeout(()=>{
                    this.visible = false;
                },2000)
            },
        },
        mounted() {
            this.close();
        }
    }
</script>

再創(chuàng)建一個main.js

import Vue from 'vue';
let AlertConstructor = Vue.extend(require('./main.vue'));
let instance;
var Alert= function (msg) {
    instance = new AlertConstructor({
        data: {
            message: msg
        }
    });
    instance.$mount();
    document.body.appendChild(instance.$el);
    return instance;
};
export default Alert;

在主入口main.js引入組件:

import Alertfrom './alert/src/main.js';
Vue.prototype.$myAlert = Alert;

然后在頁面上測試一下:

<button @click='test'>按鈕</button>
methods:{
    test(){
        this.$myAlert("hello vue");
    }
}

此時控制臺報錯:

[Vue warn]: Failed to mount component: template or render function not defined.

百思不得其解???

回答
編輯回答
病癮

注冊組件 還得掉一個vue的 install 內(nèi)置方法

//alert里面的main.js
import Vue from 'vue'
import alertComponent from './main.vue'
let AlertConstructor = Vue.extend(alertComponent);
let instance;
var Alert= function (msg) {
    instance = new AlertConstructor({
        data: {
            message: msg
        }
    });
    instance.$mount();
    document.body.appendChild(instance.$el);
    // return instance;  //不需要return了  你都聲明全局變量了
};

const install = function(Vue) {  //必須要使用這個方法掛載到vue上
    Vue.prototype.$myAlert = Alert;
}
export default install
// export default Alert;
//主入口main.js這么引用
import Alertfrom from './alert/src/main.js';
Vue.use(Alertfrom);

然后就可以在別的組件里通過 this.$myAlert()調(diào)用了
這里面有比較完整的示例代碼,你可以看看

2017年12月8日 05:53