0
votes

I have a container component with a navbar component inside of it. I call an api in beforeCreate, then set variables here, and set them in vue 'state' (data), then pass those as props down to the navbar component. However, these do not appear. What am i doing wrong here?

<template>
<Navbar :title='title' />
<template>

<script>
export default{
name:'example',
data(){
    return{
        title:''
    };
},
beforeCreate: function(){
    axios.post('')
    .then(response => {
        this.title = response.title
   })
}
}
</script>

I have console logged the response data from the api, so i know it is producing data properly. I have also console logged the data variable 'title' in the mounted lifecycle, and it has data. But the props for the navbar are still empty.

2
You are missing an enclosing export default { } inside your <script> tag. Is it by mistake? - Saksham
sorry, this is just an example. i have that in my actual code. - Josh Winters
can you create a sample sandbox? - Saksham
try to add your axios request in created method instead of beforecreate - Joseph
@tao None of the answers are correct. Axios uses promises and retrieves the response asynchronously, regardless of cache. this.title = response.title is guaranteed to be evaluated after the component is mounted. It's misleading to use beforeCreated for this but it's certainly not an issue here. - Estus Flask

2 Answers

0
votes

beforeCreate is called before data observation. Try again using beforeMount

0
votes

Simply in the beforeCreate life cycle method your data object not loaded yet so you can't call it at this time so the best practice for this to use created method

beforeCreate()

This is the very first lifecycle hook that gets called in Vue JS, it gets called immediately after the Vue instance has been initialized.

created()

the second lifecycle hook that is called right after the beforeCreated hook. At this stage, the Vue instance has been initialized and has activated the start of things like computed properties, watchers, events, data properties and manipulations that come with it.

enter image description here

created: function(){
    axios.post('')
    .then(response => {
        this.title = response.title
   })
}