[英]How to import a external function in a Vue component?
我是 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 警告]:属性或方法“MyFunction”未在实例上定义,但在渲染期间被引用。 通过初始化该属性,确保该属性是反应性的,无论是在数据选项中,还是对于基于类的组件。 请参阅: https ://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。
我已经阅读了很多文档并且无法理解为什么它不起作用。 谁能帮我这个 ??
您正在导出一个对象,然后为了使用MyFunction
,您需要使用点表示法访问该函数,如下所示: MyFunctions.MyFunction("Please do some stuff !")
我为这个用例做了一个工作示例: 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
文件中,只要它们位于<script>
标签内即可。 由于Vue.js 毕竟是 javascript,因此在调试时应该查看的第一部分是语法是否存在某种错误。 据我所知, import
和export
语句有些混乱,一开始可能很复杂!
在模块中,我们可以使用以下内容
// module "my-module.js"
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = { /* nice big object */ }
export { cube, foo, graph };
这样,在另一个脚本中,我们可以:
import { cube, foo, graph } from 'my-module';
// Use your functions wisely
您导出的是一个对象,而您使用的是该对象内部的一个字段/方法,因此您需要以这种方式使用您的函数:
MyFunctions.MyFunction("Please do some stuff !");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.