我是 javascript 和 vue.js 的新手,在尝试在现有程序中添加新功能时遇到了一些问题。
我已将我的新函数(与其他函数)放在一个单独的文件中:
export const MyFunctions = {
MyFunction: function(param) {
// Doing stuff
}
}
然后我将文件导入组件文件并调用我的函数:
<script>
import {MyFunctions} from "@/components/MyFunctions.js";
export default {
name:"Miniature",
computed: {
useMyFunction() {
MyFunction("Please do some stuff !");
}
}
}
</script>
当组件被使用时,我得到一个错误信息
[Vue warn]: Property or method "MyFunction" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
我阅读了很多文档,但不明白为什么它不起作用。谁能帮我解决这个问题??
最佳答案
您正在导出一个对象,然后为了使用 MyFunction
,您需要使用点符号访问该函数,如下所示:MyFunctions.MyFunction("请做一些事情! ")
我为这个用例做了一个工作示例:https://codesandbox.io/s/62l1j19rvw
MyFunctions.js
export const MyFunctions = {
MyFunction: function(param) {
alert(param);
}
};
组件
<template>
<div class="hello">
{{msg}}
<button @click="handleClick">Click me</button>
</div>
</template>
<script>
import {MyFunctions} from "../MyFunctions.js";
export default {
name: "HelloWorld",
data() {
return {
msg: "Welcome to Your Vue.js App"
};
},
methods:{
handleClick: function(){
MyFunctions.MyFunction("Please do some stuff !");
}
}
};
</script>
关于javascript - 如何在Vue组件中导入外部函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777182/