简体   繁体   中英

Vuex state change doesn't make component re-render?

I have a navbar which has conditional rendering depending on authentication:

<template>
  <div id="routing">
    <b-navbar variant="light" type="light">
      <b-navbar-brand>
        <img id="drage" src="../assets/icon.svg"/>
        <b-nav-text id="txt">
          drac1
        </b-nav-text>
        <div v-if="loggedIn === true">
          <router-link id="link" to="/" exact>
            Home
          </router-link>
          <router-link id="link" to="configuration" exact>
            Config
          </router-link>
          <b-nav-text id="hellotext">
            Hello, {{ username }}
          </b-nav-text>
        </div>
      </b-navbar-brand>
    </b-navbar>
  </div>
</template>

<script>
  export default {
    name: 'topnavbar',
    data () {
      console.log(this.$store.state.loggedIn) // Changes from false to true as it is supposed to, and logs it. 
      return {
        username: this.$store.state.username,
        loggedIn: this.$store.state.loggedIn
      }
    }
  }
</script>

THe value loggedIn which the conditional render depends upon does change from false to true when the user has logged in. However, the router-link items as well as the username nav text never show up.

Why doesn't a change in store state trigger a re-render of the navbar in this case?

You are using it wrong, in order for the changes to be reflected you need to use computed properties:

 export default {
    name: 'topnavbar',
    data () {

      return {

      }
    },

    computed: {
        username(){
            return  this.$store.state.username
        },
        loggedIn(){
            return  this.$store.state.loggedIn
        }
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM