VUE:从toast组件到toast插件(二)

在上一篇文章当中,我们简述了在vue的项目中toast组件的使用,可以说是非常麻烦,现在我就来简述一下如何搞一个toast插件。

其实比较理想的使用方式是在项目中随心所欲的使用,如:this.$toast.show("展示的内容", 多长时间后关闭)。

一、改造Toast.vue

//components/common/toast/Toast.vue

<template>
  <div class="toast-box" v-show="isShow">
    <div>{{content}}</div>
  </div>
</template>

<script>
export default {
  name: "Toast",
  data() {
    return {
      isShow: false,
      content: "",
      times: null
    };
  },
  methods: {
    show(text = "操作成功", duraction = 3) {
      this.content = text;
      this.isShow = true;
      if (this.times) clearTimeout(this.times);
      this.times = setTimeout(() => {
        this.content = "";
        this.isShow = false;
      }, duraction * 1000);
    }
  }
};
</script>

<style lang="scss" scoped>
.toast-box {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 99999;

  max-width: 80%;
  height: auto;
  padding: 2rem 2rem;
  box-sizing: border-box;
  border-radius: 0.5rem;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}
</style>

上面是在Toast组件中写了一个show方法,自主控制显示和隐藏;

二、关键的一步,在同级目录下创建一个插件入口文件index.js

//components/common/toast/index.js

import Toast from './Toast.vue';

const obj = {};

obj.install = function(Vue){
    // 1.创建组件构造器
    const toastContrustor = Vue.extend(Toast);
    // 2.new的方式,根据组件构造器,可以创建出一个组件对象
    const toast = new toastContrustor();
    // 3.将组件对象,手动挂载到某一个元素上
    toast.$mount(document.createElement('div'))
    // 4.toast.$el对应的就是div
    document.body.appendChild(toast.$el)

    Vue.prototype.$toast = toast;
}

export default obj;

每一步的注释我都写上去了,不要问为什么,问了就是不知道;

三、在项目入口文件main.js引入并使用

// main.js

import Vue from 'vue';
import toast from 'common/toast';

Vue.use(toast);

四、接下来,就是随心所欲的使用了

// views/home/Home.vue

<template>
    <div class="home">
        <button @click.stop = "showToast" >点击显示toast</button>
    </div>
</template>

<script>
export default {
    name: "Home",
    components:{
        Toast,
    },
    methods:{
        showToast(){
            this.$toast.show("这是一个toast", 3)
        }
    }
}
</script>

基本上四部就可以搞定了,如果有啥疑问,欢迎交流,最后感谢coderwhy老师!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值