0

This is a simple component. I'm trying to assign props to data as docs said so. (the initialData comes from vuex and database)

<template>
    <section>
        {{ initialData }}
        {{ privateData }}
    </section>
</template>

<script>
export default {
    name: 'someName',
    props: [
        'initialData'
    ],
    data() {
        return {
            privateData: this.initialData
        };
    }
 };

But, the problem is initialData is OK, but privateData is just an empty object {}.

Weirdest thing is, if I save my file again, so webpack hot reloads stuff, privateData also gets the proper data I need.

Here is the parent:

<template>
    <section v-if="initialData">
        <child :initial-data="initialData"></micro-movies>
    </section>
</template>

<script>
export default {
    name: 'parentName',
    data() {
        return {};
    },
    computed: {
        initialData() {
            return this.$store.state.initialData;
        }
    },
    components: {
        child
    }
};
</script>

I know that it's about getting data dynamically . because if I change initialData in parent to some object manually, it works fine.

tony19
  • 125,647
  • 18
  • 229
  • 307
Mehdi Hoseini
  • 407
  • 1
  • 4
  • 12
  • Use computed properties if your data is dependent on other data/property – Rakesh Soni Dec 16 '17 at 15:52
  • Could you also show the code where you are passing the prop from the parent? The code here looks ok. – Sergo Pasoevi Dec 16 '17 at 15:52
  • @RakeshSoni I did. and it works fine. but every data change needs `forceUpdate()`. I'm trying to change it to `data` so it auto update the component. – Mehdi Hoseini Dec 16 '17 at 16:06
  • @SergiPasoev Ok. (It's something about getting data dynamically) – Mehdi Hoseini Dec 16 '17 at 16:06
  • The data function is only ever called *once* at component creation. If `initialData` is not populated at that point in time, then `privateData` will always be null. That is why you probably want to use a computed property, or watch the property. – Bert Dec 16 '17 at 17:39
  • @Bert You're right. wanna write it as answer so I can mark it? – Mehdi Hoseini Dec 16 '17 at 17:57

1 Answers1

2

The data function is only ever called once at component creation. If initialData is not populated at that point in time, then privateData will always be null. That is why you probably want to use a computed property, or watch the property.

Bert
  • 80,741
  • 17
  • 199
  • 164