2
votes

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.

2
getLists(), not this.getLists().str
If you do want them to be methods, you might want to make a mixinRoy J

2 Answers

4
votes

I guess 2 things should be fixed:

  1. 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 }
  1. Second thing, import them and use without this, like below:
...
<script>
import { sendList, getLists, deleteList } from '../statics/functions.js'
...
created() { getLists() },
...
0
votes

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?