Vue.js:导入带有函数的类并在子组件中调用它 [英] Vue.js: Import class with function and call it in child component
问题描述
我有一个组件我的父母
。在此组件中,我使用子组件 my-child
并导入具有自己的函数<$的外部类 MyClass
c $ c> 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
很容易,我使用 mount
和来自导入类的函数名称。在方法
中,我定义了一个新方法,该方法从导入的类中调用已装入的方法。比起将创建的方法作为属性传递给我的孩子,在这里我尝试用 @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屋!