天天看点

用vue编写带动画效果的toast

Aniamted

为了方便快速的使用动画,我们可以使用现成的轮子–

npm install animate.css
           

Start

vue官方文档给我们指出了编写插件的步骤和一些参数,这里提供给一个编写toast的模板:

import animated from 'animate.css'

let Toast = {};
Toast.install = function(Vue,options){
    let opt ={
      type:"text",
      text:"这是一条默认的toast",
      position:"middle",
      duration:"2500"
    };

    if(options){
      Object.keys(options).forEach(key =>{
        opt[key] = options[key];
      });
    }

    Vue.prototype.$toast = op=>{

      if(typeof op ==='string'){
        opt.text = op;
      }else if(typeof op ==='object'){
        Object.keys(op).forEach(key =>{
          opt[key] = op[key];
        });//会保存上次使用toast的text
      }


      if(document.getElementsByClassName("ys-toast").length){
        return;
      }

      let toastTemplate = Vue.extend({
        template: `<div class="ys-toast animated fadeIn">
                        <p>${opt.text}</p>
                    </div>`
      });
      let toastEle = new toastTemplate().$mount().$el;
      document.body.appendChild(toastEle);
      setTimeout(function () {
        document.body.removeChild(toastEle);
      },opt.duration);
    }

};

export{
  Toast
}

           

How to use ?

在main.js中引用:

import {Toast} from './plugins/toast/toast'
Vue.use(Toast);//需要在new Vue({})之前调用
           

When will it be called?

toast一般是用来提示网络信息的,所以一般可以配合vuex的异步action来使用。

所以我们需要在调用action的时候将this通过context参数传进去,否则无法调用toast!毕竟插件是install在vue原型上的==

setSwiper({commit,state},context){
    _get({
      url:`${GET.Slides}${state.storeId}`
    }).then(res=>res.json()).then(data=>{
      let list = [];
      if(data['data'].length){
        data['data'].forEach((item,index)=>{
          list.push({
            id:index,
            src:item["slideUrl"],
            alt:item['slideId']
          });
        });
        commit(SET_SWIPER_LIST,list);
      }else{
        context.$toast(`can't get the swiper data! data is null!`);
        console.warn("swiper list is null!");
      }
    }).catch(err=>{
       context.$toast(`Failed get swiperList! err: ${err}`);
       console.error("Failed get swiperList!",err)
    });
           

继续阅读