Vue.js:使用函数导入类并在子组件中调用它 [英] Vue.js: Import class with function and call it in child component

查看:39
本文介绍了Vue.js:使用函数导入类并在子组件中调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件 my-parent.在这个组件中,我使用一个子组件 my-child 并导入一个外部类 MyClass 和一个自己的函数 exportedFunction.我尝试使用此解决方案:VueJS 在 vue 组件中访问外部导入的方法

I have a component my-parent. In this component, I use a child component my-child and import an external class MyClass with an own function exportedFunction. I tried to use this solution: VueJS accessing externaly imported method in vue component

基本上,我使用 mounted 和导入类中的函数名称.在 methods 中,我定义了一个新方法,它从导入的类中调用挂载的方法.比我将创建的方法作为属性传递给我的孩子,在那里我尝试使用 @click 调用该函数并将参数传递给那里.

Basiclly, I use mounted and the name of the function from the imported class. In methods I defined a new method, which calls the mounted one from the imported class. Than I pass the created method as property to my child, where I try to call the function with a @click and pass the parameter there.

到目前为止,这是我的代码:

Here is my code so far:

我的父母模板:

<template>
    <my-child :exportedFunction="callFunction"></my-child>
</template>

<script>
import MyClass from './MyClass';

export default {
    mounted() {
        exportedFunction()
    },
    methods: {
        callFunction() {
            exportedFunction()
        }
    }
}
</script>

我的孩子模板:

<template>
    <button @click="exportedFunction('hello world!')">Click me!</button>
</template>

<script>
export default {
    props: ['exportedFunction']
}
</script>

MyClass 代码:

export default class MyClass {
    exportedClass(parameter) {
        console.log(parameter) // expected 'hello world' from child
    }
}

希望得到一些帮助!

推荐答案

我会放弃你的 MyClass 组件,而是拥有:

I would ditch your MyClass component and instead have:

我的父母

<template>
    <my-child :triggerEvent="callFunction"></my-child>
</template>

<script>
export default {
    methods: {
        callFunction() {
          console.log('hello');
        }
    }
}
</script>

我的孩子

<template>
    <button @click="$emit('triggerEvent')">Click me!</button>
</template>

当您想在示例中使用 MyClass 时,您可以保持原样并将 my-parent 设置为:

As you want to use MyClass in your example you can keep it as is and have my-parent as:

<template>
  <my-child :triggerEvent="callFunction"/>
</template>

<script>
import MyChild from "./MyChild";
import MyClass from "./MyClass.js";

export default {
  components: {
    MyChild
  },
  data() {
    return {
      myCls: new MyClass()
    };
  },
  mounted() {
    this.myCls.exportedClass("hello my class");
  },
  methods: {
    callFunction() {
      console.log("hello");
    }
  }
};
</script>

这篇关于Vue.js:使用函数导入类并在子组件中调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆