当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 最简单的vue消息提示全局组件的方法

最简单的vue消息提示全局组件的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

恶魔的笛子,依卡劳特,四叶草之赤沙印记

简介

实现功能

  • 自定义文本
  • 自定义类型(默认,消息,成功,警告,危险)
  • 自定义过渡时间

使用vue-cli3.0生成项目

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网