Vue2手动挂载组件$mount()学习

929 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

>>>>>>>>

        说实话,我自己在开发过程中,几乎没有使用过这个方法。是面试的时候,被问到的。所以特地学习,并记录分享一下。

官方介绍

首先我们先来看一下官方文档

在官方文档中,定义了挂载方法 vm.$mount([elementOrSelector])

接受的参数为

  • {Element | string} [elementOrSelector]
  • {boolean} [hydrating]

用法

如果 Vue 实例在实例化时没有收到 el 选项,则它处于“未挂载”状态,没有关联的 DOM 元素。可以使用 vm.$mount() 手动地挂载一个未挂载的实例。

如果没有提供 elementOrSelector 参数,模板将被渲染为文档之外的的元素,并且你必须使用原生 DOM API 把它插入文档中。

这个方法返回实例自身,因而可以链式调用其它实例方法。

同时官方还提供了示例,大家可以自己去看。这里就是根据官方的示例,仿写的。

首先,在项目中创建文件夹及文件 MyNotice/MyNotice.vue

template代码

<template>
    <div class="notice-box">
        <div class="message" 
            :class="item.type" 
            v-for="item in msgList" 
            :key="item._name"
        >
            <div class="content">{{item.content}}</div>
        </div>
    </div>
</template>

主要的实现逻辑

<script>
const DefaultOption = {
    duration: 1500,
    type: "normal",
    content: "提示内容!",
};
let idx = 0;
export default {
    data() {
        return {
            msgList: [],
        };
    },
    methods: {
        add(msgOpt = {}) {
            // name标识 用于移除弹窗
            let _name = this.getName();
            // 并入默认配置,并赋值
            msgOpt = Object.assign(
                {
                    _name,
                },
                DefaultOption,
                msgOpt
            );
            this.msgList.push(msgOpt);

            setTimeout(() => {
                this.removeMsg(_name);
            }, msgOpt.duration);
        },
        getName() {
            return "msg_" + idx++;
        },
        removeMsg(_name) {
            let index = this.msgList.findIndex((item) => item._name === _name);
            this.msgList.splice(index, 1);
        },
    },
};
</script>

消息提示窗的样式

样式就完全是根据个人喜好来定的了,你可以按照自己的想法来写。我这里写的只是为了提供一下参考。

<style lang='scss' scoped>
.notice-box {
    position: fixed;
    top: 50px;
    left: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    transform: translateX(-50%);

    .message {
        border-width: 3px;
        min-width: 240px;
        max-width: 500px;
        margin-bottom: 10px;
        border-radius: 3px;
        box-shadow: 0 0 8px #ddd;
        overflow: hidden;

        &.normal {
            border-left: 3px solid #909399;
            background: #f4f4f5;
        }
        &.success {
            border-left: 3px solid #67c23a;
            background: #f0f9eb;
        }
        &.error {
            border-left: 3px solid #f56c6c;
            background: #fef0f0;
        }
        &.warning {
            border-left: 3px solid #e6a23c;
            background: #fdf6ec;
        }

        .content {
            padding: 8px;
            line-height: 1.3;
        }
    }
}
</style>

引入

在文件夹中新建 index.js 文件,并引入 Vue 和上面写的 MyNotice.vue

import Vue from 'vue'
import MyNotice from './MyNotice.vue'

let noticInstance = null,
    NoticeConstructor = Vue.extend(MyNotice),
    init = () => {
        noticInstance = new NoticeConstructor()
        noticInstance.$mount()
        document.body.appendChild(noticInstance.$el)
    },
    caller = (opt) => {
        if (!noticInstance) {
            init()
        }
        noticInstance.add(opt)
    }

export default {
    // 返回 install 函数 用于 Vue.use 注册
    install(vue) {
        vue.prototype.$notice = caller
    },
}

在项目的main.js文件中,引入我们写的组件

import MyNotice from '@/components/MyNotice/index.js'

Vue.use(MyNotice)

调用

 myNotice() {
    this.$notice({
        type: "success",
        content: "成功信息提示",
        duration: 2000,
    })
 }