1.首先新建一个Cmponent.vue文件
<template>
<div class="toast" v-show="isShow">
<div>{{ message }}</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
message: "",
isShow: false,
};
},
methods: {
show(message, duration) {
this.isShow = true;
this.message = message;
setTimeout(() => {
this.isShow = false;
this.message = '';
}, duration);
},
},
};
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 8px 10px;
color: #fff;
background-color: rgba(0, 0, 0, 0.75);
z-index: 999;
border: 1px solid #000;
border-radius: 8px;
}
</style>
2.其次在同一目录下建立index.js文件,在这个文件中使用install方法来全局注册该组件
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.component('toast', obj)
// 在vue原型上添加$toast,方便以后组件使用
Vue.prototype.$toast = toast;
}
export default obj
3.在main.js文件中 安装toast插件
// 只要在index.js里规定了install方法,就可以向其他ui组件库那样,使用Vue.use()来全局使用
//main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import toast from 'components/common/toast'
// 安装toast插件
Vue.use(toast);
Vue.prototype.$bus = new Vue()
// app.mount('#app')
new Vue({
render: h => h(App),
router,
store
}).$mount('#app')
4.在组件中使用
// detail组件中使用,部分代码
this.addCart(product).then(res => {
// console.log(res);
this.$toast.show(res,2000);
})
addCart(context, payload) {
return new Promise((resolve, reject) => {
// 1.查找之前数组中是否有该商品
let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)
// 2.判断oldproduct
if (oldProduct) {
// oldProduct.count += 1
context.commit(ADD_COUNTER, oldProduct)
resolve('当前商品数量+1')
} else {
payload.count = 1
// context.state.cartList.push(payload)
context.commit(ADD_TO_CART, payload)
resolve('添加了新的商品')
}
})
}