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.
I tried this:
functions.js
function sendList() {...};
function getLists() {...};
function deleteList(listId) {...}
export default {sendList, getLists, deleteList}
MyLayout.vue
...
<script>
import {sendList, getLists, deleteList} from '../statics/functions.js'
...
created() { this.getLists();},
...
3 errors appear:
vue.runtime.esm.js?2b0e:587 [Vue warn]: Error in created hook: "TypeError: this.getLists is not a function"
TypeError: this.getLists is not a function
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.
I guess 2 things should be fixed:
- 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 }
...or even more prettier using ES6 syntax:
const sendList = () => {...};
const getLists = () => {...};
const deleteList = (listId) => {...}
export { sendList, getLists, deleteList }
- Second thing, import them and use without
this
, like below:
...
<script>
import { sendList, getLists, deleteList } from '../statics/functions.js'
...
created() { getLists() },
...
The other answerer is correct that you need to be using export
instead of export default
.
If you really need them to be methods on the component instance, after importing them, you can add them to the methods like so:
methods: {
deleteList,
sendList,
getLists,
anotherFunction() {
...
},
}
and then they will be accessible as this.getLists()
and so on. It will still be several lines of code (one for each method you're importing), but way fewer than having the method and all the associated logic.
Oh, and as for the third error, the not defined on the instance but referenced during render
? That happens when you've got something in the template that hasn't been properly defined in the script part. Did you type lists
somewhere you meant to type list
?