vue如何实现消息提示全局组件

发布时间:2021-08-18 10:06:22 作者:小新
来源:亿速云 阅读:247

这篇文章主要介绍了vue如何实现消息提示全局组件,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

使用vue-cli3.0生成项目

vue如何实现消息提示全局组件

vue如何实现消息提示全局组件

toast全局组件编写

/src/toast/toast.vue

<template>
 <div class="app-toast"
    v-if="isShow"
    :class="{'info': type=== 'info','success': type=== 'success','wraning': type=== 'wraning','danger': type=== 'danger'}">{{text}}</div>
</template>
<style scoped>
.app-toast {
 position: fixed;
 left: 50%;
 top: 50%;
 background: #ccc;
 padding: 10px;
 border-radius: 5px;
 transform: translate(-50%, -50%);
 color: #fff;
}
.info {
 background: #00aaee;
}
.success {
 background: #00ee6b;
}
.wraning {
 background: #eea300;
}
.danger {
 background: #ee000c;
}
</style>

/src/toast/index.js

import vue from 'vue'
import toastComponent from './toast.vue'

// 组件构造器,构造出一个 vue组件实例
const ToastConstructor = vue.extend(toastComponent)

function showToast ({ text, type, duration = 2000 }) {
 const toastDom = new ToastConstructor({
  el: document.createElement('div'),
  data () {
   return {
    isShow: true, // 是否显示
    text: text, // 文本内容
    type: type // 类型
   }
  }
 })
 // 添加节点
 document.body.appendChild(toastDom.$el)
 // 过渡时间
 setTimeout(() => {
  toastDom.isShow = false
 }, duration)
}
// 全局注册
function registryToast () {
 vue.prototype.$toast = showToast
}

export default registryToast

全局注册

/main.js

import toastRegistry from './toast/index'
Vue.use(toastRegistry)

调用

/src/views/home.vue

<template>
 <div class="home">
  <input type="button"
      value="显示弹窗"
      @click="showToast">
 </div>
</template>

<script>

export default {
 name: 'home',
 methods: {
  showToast () {
   this.$toast({
    text: '我是消息'
    // type: 'wraning',
    // duration: 3000
   })
  }
 }
}
</script>

感谢你能够认真阅读完这篇文章,希望小编分享的“vue如何实现消息提示全局组件”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. vue中全局组件和局部组件是什么
  2. VUE中怎么注册全局组件和局部组件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:db2死锁监视器的使用方法

下一篇:vue中如何实现基于axios的ajax请求方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》