最近学习使用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插件。