[英]Vue.js: Import class with function and call it in child component
我有一個組件my-parent
。 在這部分中,我使用一個子組件my-child
和導入外部類MyClass
有自己的功能exportedFunction
。 我嘗試使用此解決方案: VueJS訪問vue組件中的外部導入方法
基本上,我使用導入的類中的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
}
}
希望能有所幫助!
我將放棄您的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>
當您想在示例中使用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.