【发布时间】:2019-10-11 02:27:04
【问题描述】:
我有一个组件my-parent。在这个组件中,我使用了一个子组件my-child 并导入了一个外部类MyClass 和一个自己的函数exportedFunction。我尝试使用此解决方案:VueJS accessing externaly imported method in vue component
基本上,我使用mounted 和导入类中的函数名称。在methods 中,我定义了一个新方法,它从导入的类中调用挂载的方法。然后我将创建的方法作为属性传递给我的孩子,在那里我尝试使用@click 调用该函数并在那里传递参数。
到目前为止,这是我的代码:
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>
<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
}
}
希望得到一些帮助!
【问题讨论】:
-
有什么理由为什么在子组件中你不发出你在父组件中监听的事件并在那里触发方法?
-
@Manu 因为我真的是 Vue.Js 的新手,所以不知道有这样的方法。在这个例子中我该怎么做?
标签: javascript class vue.js properties vue-component