【问题标题】:VueJS define global function for child componentsVueJS 为子组件定义全局函数
【发布时间】:2022-07-22 23:16:10
【问题描述】:

谁能帮我配置一个全局函数,我可以在我的所有 Vue 文件中调用它?

当我的 Vue 文件中有这个时: @click="ModalShow.show('my-create')"

app.js我定义了这个常量:

const Modals = {
    show(screen) {
      alert(screen);
      // other logic that i implement that should be triggered
    },
};

但我不断得到: TypeError: undefined is not an object (evaluating '_ctx.Modals.show')

我错过了什么?这是一个带有组合 API 的 Vue 项目

【问题讨论】:

    标签: javascript typescript vue.js vuejs3


    【解决方案1】:

    如果您希望在所有文件中都存在全局function,则需要设置全局mixin,并在其中设置此function

    例如:

    funcitonMixin.js

    export default {
      methods() {
        show(screen) {
          alert(screen);
          // other logic that i implement that should be triggered
        },
      }
    }
    

    App.js 从“路径/到/文件夹”导入 funcitonMixin

    createApp({
      ...other properties
      mixins: [funcitonMixin],
    }).mount('#app')
    

    【讨论】:

      【解决方案2】:

      您可以将您的功能提供给您的子组件

      createApp({
        ...
        provide: {
          Modal: {
            show() {
              ...
            }
          }
        }
      }
      

      然后将其注入到您的组件中

      import { inject } from 'vue'
      
      export default {
        setup() {
          const message = inject('Modal')
          return { Modal }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-24
        • 1970-01-01
        • 2020-10-29
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多