在Vue中自定义一个消息提示

实现一个消息组件

1.在components文件下创建一个Message.vue的组件

<template>
  <div class="message-box">
    <div class="message-success" v-if="type === 'success'">{{ content }}</div>
    <div class="message-error" v-if="type === 'error'">{{ content }}</div>
  </div>
</template>

<script>
export default {
  name: 'Message',
  data() {
    return {
      type: '', // 接收一个参数,显示不同的消息框
      content: '', // 将要显示消息内容
      duration: 3000 // 消息框显示时间
    }
  },
  mounted() {
  	// 消息框定时隐藏
    setTimeout(() => {
      // 隐藏时卸载掉dom
      this.$destroy(true)
      this.$el.parentNode.removeChild(this.$el)
    }, this.duration)
  }
}
</script>

<style scoped>
/* 消息框的样式,采用fixed定位 */
.message-box {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 40px;
  left: 0;
  right: 0;
  color: #fff;
  z-index: 9999;
  background: transparent;
}
</style>

实现调用函数

在同目录下创建一个Message.js的js文件

import Vue from "vue"; // 引入 Vue 是因为要用到 Vue.extend() 这个方法
import message from "./Message.vue"; // 引入刚才的 toast 组件


const Toast = function () {
  instance = new ToastConstructor().$mount(); // 渲染组件
};

let messageConstructor = Vue.extend(message); // 这个在前面的前置知识内容里面有讲到
let instance;

const Message = function (options = {}) {
  instance = new messageConstructor({
    data: options // 这里的 data 会传到 message.vue 组件中的 data 中,当然也可以写在 props 里
  }); // 渲染组件
  document.body.appendChild(instance.$mount().$el); // 挂载到 body 下
};

// 在这里将调用的方法分为两类
["success", "error"].forEach(type => {
  Message[type] = options => {
    options.type = type;
    return Message(options);
  };
})
export default Message;

在入口文件main.js内引入和绑定消息组件

import message from './components/Message/Message'
Vue.prototype.$message = message

在其他组件内调用消息提示组件

this.$message.success({ content: '这是成功的提示' })
// this.$message.success({ content: '这是失败的提示' })
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值