vue开发插件,使用this调用组件

需求

一些常用的组件,如提示框、模态框等,为了防止频繁使用 import 引入费时费力,我们可以将其修改为使用 this + 方法名调用。

解决方案

根据需求,首先想到的就是将组件挂载到 Vue.prototype 上,所以我们可以开发 Vue 插件来完成。

插件通常用来为 Vue 添加全局功能
官方文档

接下来我们创建一个简易的提示框组件。

步骤:
src 目录下创建一个 pop 文件夹,在该文件下创建两个文件 Pop.vueindex.js

// Pop.vue
<template>
  <div
    class="tips animation"
    v-show="isShow"
    :class="{ shake: type === 'shake' }"
    ref="tips"
  >
    <div class="content">{{ msg }}</div>
  </div>
</template>

<script>
export default {
  name: 'Pop',
  props: {
    // 类型
    type: {
      type: String,
      default: ''
    },
    // 提示信息
    msg: {
      type: String,
      default: ''
    },
    // 显示隐藏
    isShow: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isShow (newval, oldval) {
      if (newval !== oldval && newval === true) {
        setTimeout(() => {
          const height = this.$refs.tips.clientHeight
          const width = this.$refs.tips.clientWidth
          this.$refs.tips.style.marginLeft = -width / 2 + 'px'
          this.$refs.tips.style.marginTop = -height / 2 + 'px'
        }, 0)
        setTimeout(() => {
          this.isShow = false
          this.msg = ''
          this.type = ''
        }, 3000)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }

  10%,
  30%,
  50%,
  70%,
  90% {
    transform: translateX(-10%);
  }
  20%,
  40%,
  60%,
  80% {
    transform: translateX(10%);
  }
}

.tips {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
.animation {
  animation-fill-mode: both;
  animation-duration: 0.3s;
}

.content {
  background: rgba($color: #000000, $alpha: 0.4);
  color: #fff;
  border-radius: 6px;
  padding: 10px 15px;
}

.shake {
  animation-name: shake;
}
</style>

下面是重点内容,开发插件。

Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

// index.js 
import PopComponent from './Pop.vue'

const Pop = {}

Pop.install = Vue => {
  const PopConstructor = Vue.extend(PopComponent)
  const instance = new PopConstructor()
  instance.$mount(document.createElement('div'))
  document.body.appendChild(instance.$el)

  Vue.prototype.$pop = (type, msg) => {
    instance.type = type
    instance.msg = msg
    instance.isShow = true
  }
}

export default Pop

最后在 main.js 中加入

// 引入js
import Pop from './components/pop'
Vue.use(Pop)

完成以上步骤,就可以在任意页面使用 this.$pop('shake', '请先登录') 使用该组件了。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值