1
votes

I have a chile vue component and a property is passed as 'initial_features'.

<child-component :initial_features="features"></child-component>

The code of my child component is:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col">
                {{ initial_features }} //this prop is working here
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        props: ['initial_features'],
        data() {
            return {
                features: this.initial_features, //undefined
            }
        },
        methods: {},
        computed: {},
        mounted() {
            console.log(this.initial_features); //output is undefined here
        }
    }
</script>

I have written this type of code many times but this time I am not getting the expected result. The props should work in the data or mounted section. Is there any mistake in my code?

1
make features: null inside your data and use created function to copy it to your features. :) - halilcakar
Not needed. You can use props to init data - Michal Levý
I tried both but got undefined - Yeasir Arafat Hridoy
what about data(vm){ return{features: vm.initial_features,};}? - Boussadjra Brahim
There si too much I don't know about your code (for example what type is initial_features prop and whats happening in parent component) but data function is called only once when component is created so if prop is updated later, it has no effect on features in data unless your passing object/array and updating that object/array instead of replacing it (which is not the case here because initial value is undefined). Add the code of parent and more details.. - Michal Levý

1 Answers

3
votes

Looks like it might be a case of data race condition.

"Initial_features" must be updated in the consumer of the component after the component is loaded, therefore, the data is set to undefined initially, you can always put a watch on initial_features and assign the data.features to the new value of initial_features.

If you want the data to track/update the prop consider the v-model property on your component here is more info