Vue encapsulates global components

Requirements: When you need to click "Online Consultation" on the company's official website, online customer service pops up. Online consultation has this function in multiple pages and locations. For convenience, it is packaged into a global component. The following is only for recording the global component method, so the component code is abbreviated

Step 1: Write a simple component first, create an online.vue under the components folder, and write the required methods directly in online.vue

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

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

<style scoped lang="less">

</style>

Step 2: Encapsulate into a global component Create an online.js under the config>plugins file

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

Step 3: Globally introduce the global component online in main.js

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')

Step 4: Use the method of global components directly to avoid multiple references to components

<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>

Guess you like

Origin blog.csdn.net/Lucky_girl_wan/article/details/129125943