0

I'm new to Vue and can't figure the following out. I have an app which connects to a JSON Api via a usePage()

usePage() let's me use "page" as an object which I can use and access inside the tag.

Like:

<p>This product costs {{page.price}} Euros and is {{page.width}} wide and {{page.colour}}</p>

However, can I access this "page" object also in the data() or methods: ?

Like:

export default {
  components: {
    …
  },
  
  // Vue 3 setup
  setup () {
    return {
      page: usePage(),
    }
  },
  
  data: function() {
    return {
      product: {
        price: this.page.price,
        width: this.page.width,
        colour: this.page.colour
      }
    };
  }
}

It seems to return undefined. Is it not possible in Vue to access the same objects outside the <template> tag than inside the <template> tag?

Thanks for any tips!

1 Answer 1

2

You should not interchange properties between setup and other options like data, methods ..., in your case you could use a computed property instead of data option :

import {computed} from 'vue'

export default {
  components: {
    …
  },
  
  // Vue 3 setup
  setup () {

   const page = usePage();
   const product= computed(()=>({
        price: page.price,
        width: page.width,
        colour: page.colour
      }))
    return {
      page,product
    }
  },
  
 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thx, ok so I always need to use reactive() to access those "global" variables/objects?
Ok, so I tried your suggestion, however it says product.price for instance is undefined which means, it can't find page.price although I'm using it within the <template> tag. A simple string works though.

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.