1
\$\begingroup\$

I have a login dialog working in vue js with typescript.

I want to trigger the open via a button on page, but also by toggling a value in the vuex store.

It is working by 2 watchers:

  1. Watching the local visible state persists the state to the store on every change
  2. Watching the store state then toggles the local visible flag.

The result is the button can open the modal, click outside the modal closes. But i can trigger the modal to be opened from the router now too from elsewhere in the app via vuex.

But... now i have to have 2 watchers running all the time. Is there a better way?

<template>
    <div>
        <el-button v-if="!authenticated" @click="visible = true">Login</el-button>
        <el-dialog :visible.sync="visible" title="Login or Register">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="Login" name="login">
                    <login-form></login-form>
                </el-tab-pane>
                <el-tab-pane label="Register" name="register">
                    <register-form></register-form>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </div>
</template>

<script lang="ts">
  import { Component, Vue, Watch } from 'vue-property-decorator';
  import { AuthenticationModule } from '@/store/modules/authentication';
  import LoginForm from '@/views/forms/LoginForm.vue';
  import RegisterForm from '@/views/forms/RegisterForm.vue';

  @Component({
    components: {
      LoginForm,
      RegisterForm,
    },
  })
  export default class AppHeaderLogin extends Vue {
    private visible: boolean = false;
    private activeTab: string = 'login';

    get authenticated() {
      return AuthenticationModule.authenticated;
    }

    get loginPrompt() {
      return AuthenticationModule.prompt.login;
    }

    @Watch('loginPrompt')
    onLoginPromptChange(value: boolean) {
      if (value !== this.visible) {
        this.visible = value;
      }
    }

    @Watch('visible')
    onVisibleChange(value: boolean) {
      // Do stuff with the watcher here.
      AuthenticationModule.TOGGLE_PROMPT_LOGIN(value);
    }
  }
</script>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.