天天看點

用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)
    });
           

繼續閱讀