I'm trying to change the id of an image after the user clicks on a button. Initially, the id of the element should be B0_h, but after the user clicks on a button, a value in an array should change to true. Initially all the array values are false, but once the value of the element in the array becomes true, the id should change to B0_v.
Using the Vue dev tools, I noticed that the value in the array is changing as expected, however, v-bind can't detect this change. From the v-bind perspective, the value of B[0] is still false. As a result, the id is still B0_h.
Here's my template:
<template>
<div>
<button type="button" id="button0" v-on:click="toggle('B0')"></button>
<img src="../assets/img1.png" alt="A" v-bind:id="[A[0] === true ? 'A0_v' : 'A0_h']" >
<img src="../assets/img2.png" alt="B" v-bind:id="[B[0] === true ? 'B0_v' : 'B0_h']">
</div>
</template>
Here's my script:
<script>
export default {
name: 'Demo',
props: {},
data: function(){
return{
A: [false,false,false,false,false,false,false,false,false],
B: [false,false,false,false,false,false,false,false,false],
playerTurn: true;
}
},
methods:
{
toggle(x)
{
if(x == 'B0' && this.playerTurn)
{
this.B[0] = true;
}
}
}
}
</script>
Any idea what I'm doing wrong in here?
This is due to the handling of changes by Vue in arrays and objects. Vue won't track the change you're making. For this purpose it offers a special method: set. It takes 3 arguments: the array (or the object) that has to be changed, the index, and the value that should be set.
In your example it'll look like this:
Vue.set(this.B, 0, true);
Put this line instead of:
this.B[0] = true;
For more information please check the official documentation. This is a short excerpt:
Vue.set( target, propertyName/index, value ) Arguments:
- {Object | Array} target
- {string | number} propertyName/index
- {any} value
Returns: the set value.
Usage:
Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With