首页 > 其他 > 详细

封装vue插件

时间:2021-03-15 00:24:15      阅读:44      评论:0      收藏:0      [点我收藏+]

封装插件

1、Toast组件

<template>
<div class="toast" v-show="isShow">
  {{message}}
</div>
</template>
?
<script>
export default {
  name: "Toast",
  data(){
    return {
      isShow: false,
      message: ‘默认消息‘
    }
  },
  methods: {
    show(message=‘默认消息‘, duration=2000){
      this.isShow = true;
      this.message = message;
      const timeId = setTimeout(()=>{
        this.isShow = false;
        this.message = ‘‘;
        clearTimeout(timeId)
      },duration)
    }
  }
}
</script>
?
<style scoped>
.toast{
  max-width: 80vw;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
 
  color: #fff;
  border-radius: 10px;
}
</style>

 

2、main.js引入

import toast from ‘components/common/toast‘
Vue.use(toast)

 

3、toast/index.js

import Toast from "./Toast";
const obj = {}
?
obj.install = function (Vue) {
// 1、创建组件构造器
const toastConstructor = Vue.extend(Toast)
?
// 2、new的方式,根据组件构造器,创建出来一个组件对象
const toast = new toastConstructor();
?
// 3、将组件对象,手动挂载到某一个元素上
toast.$mount(document.createElement(‘div‘))
 
// 4、toast.$el对应的就是div
document.body.appendChild(toast.$el)
 
// 将toast组件对象挂载到Vue实例上
Vue.prototype.$toast = toast    
};
?
export default obj

4、组件中使用

<toast/>   // 使用组件
?
import Toast from "components/common/toast/Toast";
?
component: {Toast}
?
methods: {
addCart(value){
// 调用Toast组件方法
this.$toast.show(value)
}
}

 

 

 

 

 

 

 

 

 

封装vue插件

原文:https://www.cnblogs.com/xushan03/p/14533655.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!