vue封装全局组件

22 篇文章 0 订阅

需求:公司官网中需要点击“在线咨询”的时候弹出在线客服,在线咨询多个页面多个位置都有这个功能,为方便使用封装成全局组件,下方只为记录全局组件方法故组件代码简写

第一步:先写一个简单的组件,在components文件夹下面创建一个online.vue,把所需要的方法直接写在online.vue中

<template>
  <div>在线客服组件</div>
</template>

<script>
export default {
  methods:{
    open() {
      console.log('打开在线客服')
    }
  }
}
</script>

<style scoped lang="less">

</style>

第二步:封装成全局组件 在config>plugins文件下面创建一个online.js

import Vue from 'vue'
import onlineService from '../components/online.vue'

const onlineServiceBox = new Vue(onlineService)

onlineServiceBox.$mount(document.createElement('div'))

document.body.appendChild(onlineServiceBox.$el)

export default onlineServiceBox

第三步:在main.js中全局引入全局组件online

import Vue from 'vue'
import App from './App.vue'
import onlineServiceBox from './plugins/onlineService'

Vue.prototype.$onlineServiceBox = onlineServiceBox

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

第四步:直接使用全局组件的方法,避免多次引用组件

<template>
  <div class="smartbadge-btn-s">
    <button class="smartbadge-btn smartbadge-btn1" @click="openOnline">在线咨询</button>
  </div>
</template>

export default {
  methods: {
    openOnline() {
      this.$onlineServiceBox.open()
    }
  }
}

<style lang="less" scoped>
</style>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值