美文网首页
Vue 封装自己的插件

Vue 封装自己的插件

作者: hao_developer | 来源:发表于2021-03-18 16:09 被阅读0次

效果图:


image.png

1:先创建组件,并创建index.js文件


image.png

tosi.vue文件

<template>
    <div class="toast" v-show="isShow">
      <span>你好啊</span>
    </div>
</template>

<script>
  export default {
    name: "Tosi",
    data(){
      return {
        isShow: false
      }
    },
    methods: {
      show(message, duration = 1500){
        this.isShow = true
        setTimeout(() => {
          this.isShow = false
        }, duration)

      }
    }
  }
</script>

<style scoped>
  .toast{
    background: rgba(0, 0, 0, .7);
    padding: 5px 8px;
    color: #ffffff;
    border-radius: 5px;

    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50% ,-50%);
    z-index: 10;
  }
</style>

index.js文件

import Tosi from "./Tosi";

const obj = {}

obj.install = function (Vue) {

  //1、创建组件构造器
  const toastContrustor = Vue.extend(Tosi)

  //2、new的方式,根据组件构造器,可以创建来一个组件对象
  const tosi = new toastContrustor()

  //3、将组件对象,手动挂载到某一个元素上
  tosi.$mount(document.createElement('div'))

  //4、tois.$el对应的就是div
  document.body.appendChild(tosi.$el)

  Vue.prototype.$tosi = tosi

}

export default obj

2:在main.js里面进行挂载注册

import Vue from 'vue'
import App from './App.vue'

import tosi from "./components/common/tosi"

Vue.config.productionTip = false

Vue.use(tosi)

new Vue({
  render: h => h(App)
}).$mount('#app')

3:进行调用

this.$tosi.show("你好", 2000)

相关文章

网友评论

      本文标题:Vue 封装自己的插件

      本文链接:https://www.haomeiwen.com/subject/cqcpcltx.html