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

最近学习使用vue-cl写一个商城的项目,其中封装一个toast插件这个过程我觉得非常有趣,所以想记录下来。

文章根据知识点,分两篇来写:
1.tast组件;

2.toast插件

组件写起来很简单,先在组件目录下的公共组件部分创建一个文件:

//  components/common/toast/Toast.vue

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

<script>
export default {
  name: "Toast",
  props: {
    content: {
      type: String,
      default: ""
    }
  }
};
</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效果了:

// views/home/Home.vue
<template>
    <div class="home">
        <button @click.stop = "showToast" >点击显示toast</button>
        <toast :content="message" />
    </div>
</template>

<script>
import Toast from "common/toast/Toast";

export default {
    name: "Home",
    components:{
        Toast,
    },
    data:(){
        return {
            message: "",
            times: null,
        }
    },
    methods:{
        showToast(){
            this.message = "toast显示的消息";
            if(this.times) clearTimeout(this.times);
            this.times = setTimeout(()=>{
                this.message = "";
            },3000);
        }
    }
}
</script>

以上就是写了一个toast组件,哪里需要使用,就在哪里引入,使用起来还是不太方便的。

本文章有点水,但是在下一篇文章则会记录在vue项目中如何封装一个toast插件

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值