自定义插件,封装Toast组件(Vue) 深碍√TFBOYSˉ_ 2021-07-24 22:41 472阅读 0赞 使用方法 在main.js通过Vue.use安装后,在其他组件内部,this.$toast.show(弹出内容,消失事件毫秒)使用 代码实例: main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import Toast from '@/components/common/toast/toast.vue' Vue.config.productionTip = false let plugins={ install(Vue) { //创建组件构造器 let Profile=Vue.extend(Toast); //创建组件对象,具有了$el获取组件内部dom let toast=new Profile() console.log(toast); //将组件对象挂载到任意元素,不能是文档流已有元素,因为会替换 toast.$mount(document.createElement('div')); //会替换挂载的元素,所以$el为当前组件dom document.body.appendChild(toast.$el) Vue.prototype.$toast=toast; } } Vue.use(plugins); /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>', store }) Toast组件: <template> <div class='toast' v-show='hidde'> <div class='toast-cont'> { { text}} </div> </div> </template> <script> export default { name:'toast', data(){ return{ hidde:false, text:'', time:1000 } }, methods:{ show(text,time) { this.hidde=true; this.text=text; this.time=time; setTimeout(()=>{ this.hidde=false },this.time) } } } </script> <style scoped> .toast{ position: absolute; z-index: 999; text-align: center; height: 40px; background-color: #3D3F41; width:150px; top:50%; left:50%; transform: translate(-50%,-50%); border-radius:10px } .toast-cont{ line-height: 40px; color:white; } </style> 使用: this.$toast.show('加入购物车成功',2000);
还没有评论,来说两句吧...