普通封装:
Toast.vue:
<template>
<div class="toast">
{{msg}}
</div>
</template>
<script>
export default {
name: 'Toast',
props: {
msg: String
}
}
</script>
<style scoped>
.toast {
padding: 15px 20px;
background-color: rgba(0, 0, 0, .5);
border-radius: 10%;
color: #fff;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
使用:
引入 import Toast from '...'
<Toast :msg="msg"
v-show="isShowToast"/>
//加入购物车
addCar() {
this.msg = 'hello 你好啊'
this.isShowToast = true;
setTimeout(() => {
this.isShowToast = false;
this.msg = '';
}, 300);
插件方式封装:
首先和Toast.vue同级,在toast文件夹下新建一个index文件,
然后在main文件中导入此js文件,并且使用Vue.use(Toast)安装
当执行 Vue.use() 时,就会执行install 函数,
利用此方式,在index 的install方法中设置
--main.js:
import Toast from '...'
Vue.use(Toast);
-- index.js:
const obj = {};
import Toast from './Toast.vue'
obj.install = function (Vue) { //默认有Vue参数
const vueConstructor = Vue.extend(Toast);
const toast = new vueConstructor();
toast.$mount(document.createElement('div'));
document.body.appendChild(toast.$el);
Vue.prototype.$toast = toast;
};
export default obj;
--Toast.vue:
<template>
<div class="toast" v-show="isShowToast">
{{msg}}
</div>
</template>
<script>
export default {
name: 'Toast',
data: function () {
return {
msg: '',
isShowToast: false
}
},
methods: {
show(msg, duration) {
duration = duration || 500;
this.msg = msg;
this.isShowToast = true;
setTimeout(() => {
this.isShowToast = false;
this.msg = '';
}, duration);
}
}
}
</script>
<style scoped>
.toast {
position: fixed;
background-color: rgba(0, 0, 0, .6);
padding: 10px 15px;
color: #fff;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
---使用:
this.$toast.show( ' 内容 ', 时间)