[Vuejs]-Vue variables not reactive in children of extended TypeScript parent class

1πŸ‘

βœ…

It seems I did not understand the use of extending classes in Vue/TypeScript correctly. The variable data is not shared amongst all classes that extend the parent class (ChatParent), which is why the variables did not trigger DOM changes.

I solved this problem by using Vuex as follows:

  class ChatModule extends VuexModule {
  // Variables
  chatClient!: ChatClient;
  subscribed: boolean = false;
  username: string = "";
  messages: string = "";

  // Getters
  get getUsername(): string {
    return this.username;
  }

  get getMessages(): string {
    return this.messages;
  }

  get isSubscribed(): boolean {
    return this.subscribed;
  }

  // Mutations and Actions 
  ...

  export default getModule(ChatModule);
}

The Vuex store contains all the variables. The TypeBox.vue component now simply extends Vue and calls store actions/getters:

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import chat from "@/store/modules/chat";
@Component({
  name: "TypeBox"
})
export default class TypeBox extends Vue {
  private message: string = "";
  clearMessage(): void {
    this.message = "";
  }
  sendMessage(message: string): void {
    chat.sendMessage(message);
  }
  get isSubscribed(): boolean {
    return chat.isSubscribed;
  }
}
</script>

The Vuex store actions/getters/mutations can be made Type Safe by using the vuex-module-decorators npm module.

For more details, see my GitHub repository.

3πŸ‘

My guess is that some data from one of your classes may be undefined .In that case your data won’t be reactive (see: https://github.com/vuejs/vue-class-component#undefined-will-not-be-reactive ) . you could try to use this syntax e.g username: string = null!

πŸ‘€Alex Profir

Leave a comment