自定义插件,封装Toast组件(Vue)

使用方法

	在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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值