Reputation: 141
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:
increaseYear1()
directly increases the attribute.increaseYear2()
calls increaseYear1()
but bound in the constructor to an attribute of the object.increaseYear3()
calls increaseYear1()
but the bind is done in the method itself.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
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
Upvotes: 1