vue3挂载全局方法和组件

话不多说直接上代码

main.js

import {
    
     createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

// 注册全局方法和组件
function myMethod(){
    
    
  console.log('Hello, world!');
}
app.provide("myMethod", myMethod) // provide注册全局方法 inject获取
import _ from 'lodash' // lodash方法
app.provide("_", _)

// 注册方法2
app.config.globalProperties.$user = {
    
    
  name: '蔡徐坤',
  title: '唱跳rap'
}

// component全局组件注册--------------------------------------------------注意公共组件自己写一个
import JgEmpty from '@/components/empty/index.vue'
app.component("JgEmpty", JgEmpty)

app.mount('#app')

具体某个A.vue页使用

<template>
  <div>
    <!-- 全局组件直接使用 -->
    <JgEmpty :description="'无数据'" />

    <!-- lodash使用 -->
    <div>{
    
    {
    
     _.round(1.2344,3) }}</div>
  </div>
</template>
<script>
import {
    
    defineComponent, inject} from 'vue' // 按需引入ref函数
export default defineComponent({
    
    
  components: {
    
    
  },
  name: 'testPage',
  setup() {
    
    
    let myMethod = inject("myMethod")      //  通过 inject 可以获取到 全局实例上 通过 provide  所注入的参数值。
    myMethod()

    let _ = inject("_")

	// 使用全局方法2
    const cns = getCurrentInstance()
    console.log(cns.appContext.config.globalProperties.$user)
    // or
    const {
    
     proxy } = getCurrentInstance()
    console.log(proxy.$user)

    // 将变量和函数返回,以便在模版中使用
    return {
    
    
      myMethod,
      _,
    }
  }
})
</script>


猜你喜欢

转载自blog.csdn.net/i_am_a_div/article/details/132274707