如何在外部 .js 文件中分离 .vue 组件的方法? [英] How to separate the methods of a .vue component in an external .js file?
问题描述
我的组件留下了多行代码,所以我决定将这些方法放在一个名为 functions.js 的单独文件中.我不能调用这些方法.
My component was left with many lines of code, so I decided to put the methods in a separate file called functions.js. I can not call those methods.
我试过了:
functions.js
functions.js
function sendList() {...};
function getLists() {...};
function deleteList(listId) {...}
export default {sendList, getLists, deleteList}
MyLayout.vue
MyLayout.vue
...
<script>
import {sendList, getLists, deleteList} from '../statics/functions.js'
...
created() { this.getLists();},
...
出现 3 个错误:
vue.runtime.esm.js?2b0e:587 [Vue 警告]:创建的钩子出错:TypeError: this.getLists is not a function"
vue.runtime.esm.js?2b0e:587 [Vue warn]: Error in created hook: "TypeError: this.getLists is not a function"
TypeError: this.getLists 不是函数
TypeError: this.getLists is not a function
属性或方法列表"未在实例上定义,但在渲染期间被引用.通过初始化属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件.请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
Property or method "lists" 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://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
推荐答案
我想应该修复两件事:
- 首先要确保在你的functions.js 文件中没有
default
导出,如下所示:
- First thing is to make sure to export without
default
in your functions.js file, like below:
function sendList() {...};
function getLists() {...};
function deleteList(listId) {...}
export { sendList, getLists, deleteList }
...或者使用 ES6 语法更漂亮:
...or even more prettier using ES6 syntax:
const sendList = () => {...};
const getLists = () => {...};
const deleteList = (listId) => {...}
export { sendList, getLists, deleteList }
- 第二件事,导入它们并在没有
this
的情况下使用,如下所示:
- Second thing, import them and use without
this
, like below:
...
<script>
import { sendList, getLists, deleteList } from '../statics/functions.js'
...
created() { getLists() },
...
这篇关于如何在外部 .js 文件中分离 .vue 组件的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!