vue封装全局组件

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

第一步:先写一个简单的组件,在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>

猜你喜欢

转载自blog.csdn.net/Lucky_girl_wan/article/details/129125943