rideron89
rideron89

Reputation: 531

Don't watch a data item in a Vue component

What is the best practice of preventing my component from doing an update when a particular data item is updated?

I have a Vue component with the following properties:

data: function() {
    return {
        'orderBy': 'date_published:desc',
        'page': 1,
        'posts': []
    }
},

updated() {
    this.loadPosts();
},

methods: {
    loadPosts: function() {
        // code to AJAX in data
        this.posts = response.data;
    }
}

In the component, I have buttons that change the value of orderBy and page. When these values change, I want the updated() method to be called. However, I do not want it to be called when posts changes because an infinite loop will occur.

What is the best way of telling the component to stop updating when either loadPosts() is called, or this.posts changes.

Upvotes: 0

Views: 1566

Answers (1)

Eric Guan
Eric Guan

Reputation: 15982

Combine all the properties you want to watch into a computed property, then watch the computed property

data: function() {
    return {
        'orderBy': 'date_published:desc',
        'page': 1,
        'posts': []
    }
},

computed: {
    controls(){
        return {
            orderBy: this.orderBy,
            page: this.page
        }
    }
},
watch:{
    controls(){
        this.loadPosts()
    }
},
methods: {
    loadPosts: function() {
        // code to AJAX in data
        this.posts = response.data;
    }
}

Upvotes: 4

Related Questions