toast提示插件

阅读: 4916    发布时间: 2018-09-05 14:17:01

github地址:https://github.com/501351981/vue_yii_cms

后台离不开toast提示,比如错误提示、成功提示、普通提示等,几乎每个页面都会用到,如果是开发一个toast的组件,则每个页面都要引入这个组件,使用起来过于繁琐,因此必须将toast开发成插件使用,无论在那个页面,我们只需要这样就能够调用

this.$toast({
  title: '请选择一行数据'
})

是不是很方便,接下来我们看一下vue的插件开发

我把插件都放在了src/components/plugins中,首先我们创建一个toast文件夹,然后我们再创建两个文件

index.js:插件核心代码

Toast.vue:toast组件

QQ20180905-113518@2x.png

toast组件代码

Toast.vue

<template>
  <transition name="fade">
    <div class="toast" v-show="isShow" :class="type">{{title}}</div>
  </transition>

</template>

<script>
 export default {
    name:'Toast',
 data:function () {
      return {
        title:'',
 type:'',
 isShow:false

 }
    },
 methods:{
      show:function (title,type) {
        this.title=title
        this.type=type
        this.isShow=true
 },
 hide:function () {
        this.isShow=false
 }
    }
  }
</script>

<style scoped lang="less">
 @import "../../../less/variable";
 .toast{
      display: block;
 height: 40px;
 line-height: 40px;
 padding:0 20px;
 background: rgba(76,76,76,1);
 position: absolute;
 left: 50%;
 top:50%;
 transform: translate(-50%,-50%);
 z-index: 9999;
 border-radius: 10px;
 color: white;
 font-size: 14px;
 text-align: center;
 &.error{
        background-color: red;
 }
      &.success{
        background-color: @brand-color;
 }
    }

    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s;
 }
    .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
      opacity: 0;
 }
</style>

index.js

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

let Toast={}

//插件必须有个install函数
Toast.install=function (vue) {

  //创建组件构造器
  let ToastConstructor = vue.extend(toastComponent)
  //实例化组件
  let toastDom=new ToastConstructor()
  //挂载之后,获取dom
  let tpl=toastDom.$mount().$el

  //定时器handle,再设定定时之前,清除原来的定时器
  let timeout=''

  //将组件插入页面
  document.body.appendChild(tpl)

  vue.prototype.$toast=function (options) {
    let opt={
      title:'',
      type:'',
      duration:2000
    }

    //合并参数
    Object.assign(opt,options)

    //显示toast
    toastDom.show(opt.title,opt.type)

    //定时隐藏toast
    clearTimeout(timeout)
    timeout=setTimeout(() => {toastDom.hide()} ,opt.duration)
  }
}

export default Toast

main.js

在入口文件中引用插件

import toastRegistry from './components/plugins/toast/index'

Vue.use(toastRegistry)

项目中使用

this.$toast({
  title: '请选择一行数据'
})

this.$toast({
  title:"字段不能为空",
  type:'error'
})

this.$toast({
  title:"保存成功",
  type:'success'
})


-END-