import Vue from 'vue'; import Message from './Message.vue'; // 构造组件 const MessageConstructor = Vue.extend(Message); // 设置删除组件 const removeDom = (target) => { target.parentNode.removeChild(target); }; // 构造组件添加关闭方法 MessageConstructor.prototype.close = function() { this.visible = false; removeDom(this.$el); }; const MessageDiv = (options) => { // 实例化组件 const instance = new MessageConstructor({ el: document.createElement('div'), // 组件参数,运用到组件内的data data: options, }); // 在body添加组件 document.body.appendChild(instance.$el); Vue.nextTick(() => { instance.timer = setTimeout(() => { // 定时关闭组件 instance.close(); }, 3000); }); return instance; }; export default MessageDiv;
3. 挂载 Vue.prototype
main.js :
import Message from '@/components/Message.js' Vue.prototype.$message = Message;
4. 使用:
<template> <div> <Button color="blue" @click.native="msg">我是全局按钮</Button> </div> </template> <script> import Button from "@/components/Button.vue"; export default { name: "app", components: { Button }, methods: { msg() { // 4. 使用构造组件 this.$message({value:'我是构造组件'}); } } }; </script>
效果:
以上就是三种组件的基本使用啦~~