I am facing a perplexing issue. I have a basic service and a Vue component. In the template, there is a v-if directive that monitors a variable in the service (if it is true, a div should be displayed, otherwise not). Everything works fine when I initialize the variable with a boolean value, but it fails when the variable is undefined. My method isOpened() correctly evaluates it to a boolean, so I cannot comprehend why this code is not functioning as expected. Perhaps the code snippet below can shed more light on this problem:
<template>
<div id="communicate" v-if="service.isOpened()">
This content should be displayed if the 'f' property in the service is true
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
class OtherService {
private f:boolean = false; // works fine when uncommented
//private f:boolean; // does not work when 'f' is left undefined
public info(foo:string) { this.f = true; }
public isOpened() { return (this.f === true) } // evaluates 'f' to a boolean
}
export default {
name: 'component',
data: function() {
return {
service: new OtherService()
}
},
mounted: function() {
console.log(this.service.isOpened()) // always prints false - which is expected
setTimeout(() => {
this.service.info('setting f to true') // setting 'f' to true
console.log(this.service.isOpened()) // prints true, so the div should display.
}, 2000)
}
};