develpr
develpr

Reputation: 1406

How to use Vue prop as variable in method?

I'm fairly new to Vue and am having a tough time grasping all of the concepts. I am currently building a Laravel application and am using Vue to supplement some views. What I am trying to do is a pretty simple call to my backend API with the help of a prop set up with the Vue component (Laravel Nova card).

I have an account_id that I am able to access through a prop like so:

resource.fields[3].value

I am then trying to make a call to the api and save data relevant to the account

data() {
    return {
        account: {
            name: '',
            location: '',
            type: ''
        }
    };
},

methods: {
    getAccount() {
        let vm = this;
        var account_id = vm.resource.fields[3].value;
        page_url = page_url || '/api/accounts/${account_id}';
        fetch(page_url)
        .then(res => res.json())
        .then(res => {
            this.account = res.data;
        })
        .catch(err => console.log(err));
    }
}

And then render it in my view:

<h1>{{ account.name }}</h1>
<p>{{ account.location }}</p>
<p>{{ account.type }}</p>

All of my endpoints are correct - when I visit app.dev/api/accounts/{id} I get a JSON array with all of my fields. But, I see no data in my views when I try to render it.

How can I accomplish this?

Upvotes: 0

Views: 2131

Answers (1)

ThangLe
ThangLe

Reputation: 970

I think the first you need to check the request to the server what is the URL has been requested.

So, I think in here page_url = page_url || '/api/accounts/${account_id}'; you should using the backticks (`) like this page_url = page_url || `/api/accounts/${account_id}`;

If all of these not working for you. I think you can pass it via props

data() {
    return {
        account: {
            name: '',
            location: '',
            type: ''
        }
    };
},
props: ['account_id'],
methods: {
    getAccount() {
        let vm = this;
        var account_id = vm.resource.fields[3].value;
        page_url = page_url || `/api/accounts/${this.account_id}`;
        fetch(page_url)
            .then(res => res.json())
            .then(res => {
                this.account = res.data;
            })
            .catch(err => console.log(err));
    }
}

In the caller component, using v-bind="account_id" to prop to this component.

Hope it helps you.

Upvotes: 1

Related Questions