Jérémy Halin
Jérémy Halin

Reputation: 563

How to fetch content for a component on click of a button outside this component with Vuejs?

I have a modal which I want to the content to be updated whenever I click on a button. This button is not in the component, and I need it to update an item slug, which will be used to fetch content from API.

I'm new to Vuejs.

Here is my app.js :

Vue.component('pop-modal', require('./components/PopModal.vue'));

const app = new Vue({
    el: '#app',
    data: {
        popSlug: 0
    },
    methods: {
        updatePop: function(popSlug) {
            this.popSlug = popSlug
            console.log(this.popSlug)
        }
    }
});

And here is my component:

<template>
    <div class="modal fade" id="popModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <h1>{{ pop.name }}</h1>
                <p>test: {{ this.$parent.popSlug }}</p>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                pop: {},
            }
        },
        watch: {
            popSlug(newPopslug) {
                this.popSlug = newPopslug
                this.fetchData()
                console.log('new popslug value!')
            }
        },
        mounted() {
            console.log('Component pop-modal mounted.')
        },
        methods: {
            fetchData() {
                axios.get(route('api.pops.show'), this.popSlug)
                .then(response => {
                  // JSON responses are automatically parsed.
                  this.pop = response.data
                })
                .catch(e => {
                  this.errors.push(e)
                })
                console.log('fetchData')
            }
        }
    }
</script>

I know I'm doing it wrong but I don't know how to do it right. The watch method is never triggered because popSlug is not a data attribute. I'm able to get popSlug value with:

{{ this.$parent.popSlug }}

But I think it's the wrong way to do this.

Thanks in advance for your help.

Upvotes: 0

Views: 1268

Answers (1)

Seba Arriagada
Seba Arriagada

Reputation: 380

You can pass the popSlug value as a prop to the component as explained in the documentation here. Then in the pop-modal component, you can access the value as this.popSlug and the watch will react to changes. Just make sure to don't modify the prop value inside the component, because it is supposed to be a read-only value.

Here is a working example. The internalValue is only used to show that the watch is being called. You can use anyname directly in the template.

Upvotes: 3

Related Questions