0

I'm trying to write a simple function in the methods. It should create an array out of JSON data.

The JSON object is called page with another object called images containing height, orientation etc.

setup () {
   return {
     page: usePage(),
   }
},

methods: {
   getOrientations() {
      this.page.images.forEach((item) => {
      console.log(item
  })
}

Unfortunately it throws an undefined is not an object error. Logging only this.page however prints the whole object.

Does this.page.images not work when using it inside a method? Because it works when using it "inline" in HTML.

Thanks for any tips!

2
  • What is setup? I never saw this in Vue. It should be data instead. Commented Jan 5, 2021 at 13:47
  • It's new in Vue 3 Commented Jan 5, 2021 at 14:16

1 Answer 1

3

You are currently using the Composition API (setup function) alongside the options-based API (methods object). Although it is possible, it is not recommended (take a look at their motivation). Your methods should stand in the setup function:

setup () {
  const page = usePage()
  page.images.forEach((item) => {
    console.log(item)
  })
  return {
    page,
  }
},

Of course, you could still modularize this code using functions.

setup() {
  // ...
  const getOrientations = () => {
    page.images.forEach((item) => {
      console.log(item)
    })
  }

  // And make it available to your template
  return {
    // ...
    getOrientations
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi! Ah ok, thanks for the insight! Is there a reason why the console now prints the actual code of the variable? Sorry, I'm kind of new to maybe complicated JS, maybe this is a silly question.
Unfortunately the error 'TypeError: undefined is not an object' persists even with the changed setup function
Then I think your error is not related to this problem. Could you copy the full stacktrace?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.