[英]Vue.js: Import class with function and call it in child component
I have a component my-parent
. 我有一个组件my-parent
。 In this component, I use a child component my-child
and import an external class MyClass
with an own function exportedFunction
. 在这部分中,我使用一个子组件my-child
和导入外部类MyClass
有自己的功能exportedFunction
。 I tried to use this solution: VueJS accessing externaly imported method in vue component 我尝试使用此解决方案: VueJS访问vue组件中的外部导入方法
Basiclly, I use mounted
and the name of the function from the imported class. 基本上,我使用导入的类中的mounted
和函数名。 In methods
I defined a new method, which calls the mounted one from the imported class. 在methods
我定义了一个新方法,该方法从导入的类中调用已安装的方法。 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. 然后,我将创建的方法作为属性传递给我的孩子,在这里我尝试使用@click
调用该函数并将参数传递给我的孩子。
Here is my code so far: 到目前为止,这是我的代码:
my-parent
template: my-parent
模板:
<template>
<my-child :exportedFunction="callFunction"></my-child>
</template>
<script>
import MyClass from './MyClass';
export default {
mounted() {
exportedFunction()
},
methods: {
callFunction() {
exportedFunction()
}
}
}
</script>
my-child
template: my-child
模板:
<template>
<button @click="exportedFunction('hello world!')">Click me!</button>
</template>
<script>
export default {
props: ['exportedFunction']
}
</script>
MyClass
code: MyClass
代码:
export default class MyClass {
exportedClass(parameter) {
console.log(parameter) // expected 'hello world' from child
}
}
Hope for some help! 希望能有所帮助!
I would ditch your MyClass
component and instead have: 我将放弃您的MyClass
组件,而是拥有:
my-parent
<template>
<my-child :triggerEvent="callFunction"></my-child>
</template>
<script>
export default {
methods: {
callFunction() {
console.log('hello');
}
}
}
</script>
my-child
<template>
<button @click="$emit('triggerEvent')">Click me!</button>
</template>
As you want to use MyClass
in your example you can keep it as is and have my-parent
as: 当您想在示例中使用MyClass
,可以按原样保留它,并让my-parent
为:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.