ThomasVdBerge
ThomasVdBerge

Reputation: 8140

Passing data from PHP Twig to Vue component

Relatively new to Vue. Liking it, but the info on various sources is contradictory which makes it hard to resolve issues.

I have the following code in my twig file:

<test-component data={{ test.jsonData() }}></test-component>

test.jsonData() contains the following:

"{"name":"john","lastName":"doe"}"

So far so good. My Vue component code looks like this

<template>
  <div class="test">{{ data }}</div>
</template>

<script>
export default {
    props: {
        data: {
            type: String,
            default: "{}"
        }
    },
    mounted: function () {
        console.log(this.data);
  }
};
</script>

This prints out the data as json. Now, the question is, how can I access it like data.name ? What do I need to change?

Upvotes: 1

Views: 3981

Answers (2)

whmkr
whmkr

Reputation: 3085

Don't use "data" as a prop because in vue, this.data will reference the special data store for the component. I also added a : in front of the attribute assignment as this puts the value in js context where you'd be able to define an object, an then parsed the json string there:

<test-component :person="JSON.parse({{person.jsonData()}})"></test-component>

<template>
   <div class="test">{{ test }}</div>
</template>

<script>
export default {
    props: {
        person: {
            type: Object,
            default: null
        }
    },
    mounted: function () {
        console.log(this.person);
  }
};
</script>

Upvotes: 1

matt
matt

Reputation: 700

Unless I'm misunderstanding your question, your component is receiving a data prop as a string, which is json. You could try something like this:

<template>
    <div class="test">{{ dataObj.name }}</div>
</template>

<script>
    export default {
        props: {
            data: {
                type: String,
                default: "{}"
            }
        },
        data: function() {
            return {
                dataObj: JSON.parse(this.data),
            };
        },
        mounted: function () {
            console.log(this.dataObj);
        }
    },
</script>

It seems if you are passing a JSON string to your component, you just need to parse it and store that as a data object to use in your template. You could also make a computed property from the value this way:

<template>
    <div class="test">{{ dataObj.name }}</div>
</template>

<script>
    export default {
        props: {
            data: {
                type: String,
                default: "{}"
            }
        },
        computed: {
            dataObj: function() {
                return JSON.parse(this.data);
            };
        },
        mounted: function () {
            console.log(this.dataObj);
        }
    },
</script>

Both should give you access to the properties in the JSON passed in.

Upvotes: 3

Related Questions