我是 javascript 和 vue.js 的新手,在尝试在现有程序中添加新功能时遇到了一些问题。
我已将我的新功能(与其他功能一起)放在一个单独的文件中:
export const MyFunctions = {
MyFunction: function(param) {
// Doing stuff
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在组件文件中导入文件并调用我的函数:
<script>
import {MyFunctions} from "@/components/MyFunctions.js";
export default {
name:"Miniature",
computed: {
useMyFunction() {
MyFunction("Please do some stuff !");
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
使用组件时,我收到一条错误消息
[Vue 警告]:属性或方法“MyFunction”未在实例上定义,但在渲染期间被引用。通过初始化属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件。请参阅:https : //vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。
我已经阅读了很多文档,但无法理解为什么它不起作用。谁能帮我这个 ??
Ngu*_*You 10
您正在导出一个对象,然后为了使用MyFunction您需要使用点符号访问该函数的对象,如下所示:MyFunctions.MyFunction("Please do some stuff !")
我为此用例做了一个工作示例:https : //codesandbox.io/s/62l1j19rvw
MyFunctions.js
export const MyFunctions = {
MyFunction: function(param) {
alert(param);
}
};
Run Code Online (Sandbox Code Playgroud)
成分
<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>
Run Code Online (Sandbox Code Playgroud)
您可以将 javascript 文件导入到.vue文件中,只要它们在<script>标签内即可。由于Vue.js 归根结底是 javascript,因此在调试时您应该查看的第一部分是您的语法是否存在某种错误。据我所知,importandexport语句有些混乱,一开始可能会非常复杂!
在模块中,我们可以使用以下内容
// 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 };
Run Code Online (Sandbox Code Playgroud)
这样,在另一个脚本中,我们可以:
import { cube, foo, graph } from 'my-module';
// Use your functions wisely
Run Code Online (Sandbox Code Playgroud)