Ephesiel
Ephesiel

Reputation: 141

VueJS : binded methods modify model but do not update the view

I'm new to VueJS and I created a MVC application which has a Clock. This clock updates other instanciated models of the application. But the problem is that the views of the instances are not updated...

I found the problem, it comes from binding methods. When bound methods are called, Vue doesn't know that the data changed.

Here is a simple example of the problem: This is a simple class which possesses a year, which can be increased with three methods:

export default class MyModel {
    constructor(year) {
        this.year = year
        this.function = this.increaseYear1.bind(this)
    }

    increaseYear1() {
        this.year++
    }

    increaseYear2() {
        this.function()
    }

    increaseYear3() {
        const test = this.increaseYear1.bind(this)
        test()
    }
}

Here is the view :

<template>
    {{ model.year }}<br />
    <button @click="model.increaseYear1()">Increase Year 1</button><br />
    <button @click="model.increaseYear2()">Increase Year 2</button><br />
    <button @click="model.increaseYear3()">Increase Year 3</button><br />
</template>

<script>
import MyModel from './model'

export default {
    data() {
        return {
            model: new MyModel(2021),
        }
    },
}
</script>

All methods update the value. But the second does not update the view. Why ? Is there a solution to counter that ? My entire application is based on this...

Upvotes: 0

Views: 173

Answers (1)

MohKoma
MohKoma

Reputation: 1452

If I assume that you're using VUE 3 and the states that you want to change are in their own class instance. The solution could be warp them inside reactive function.

import { reactive } from vue

export default class MyModel {
    constructor(year) {
        this.year = reactive({value: year})
        this.function = this.increaseYear1.bind(this)
    }
    ...
}

read more about reactive here https://v3.vuejs.org/guide/reactivity.html#how-rendering-reacts-to-changes

enter image description here

enter image description here

Upvotes: 1

Related Questions