admin管理员组

文章数量:1356908

I am new to Nuxt/Vue and am getting confused about how data works between different pages. I want to display a light or dark logo depending on if I am on the index page or not. When navigating between pages the data doesn't update the route name so the logo doesnt change: Layout page below.

<template>
  <main>
    <img v-if="page != 'index'" src="~/assets/img/logo-white.svg">
    <img v-else src="~/assets/img/logo-dark.svg">
    <nuxt />
  </main>
</template>

<script>
  export default {
    data () {
      return {
         page: this.$route.name
      }
    }
  }
</script>

Any help would be great. Thanks, Jamie

I am new to Nuxt/Vue and am getting confused about how data works between different pages. I want to display a light or dark logo depending on if I am on the index page or not. When navigating between pages the data doesn't update the route name so the logo doesnt change: Layout page below.

<template>
  <main>
    <img v-if="page != 'index'" src="~/assets/img/logo-white.svg">
    <img v-else src="~/assets/img/logo-dark.svg">
    <nuxt />
  </main>
</template>

<script>
  export default {
    data () {
      return {
         page: this.$route.name
      }
    }
  }
</script>

Any help would be great. Thanks, Jamie

Share Improve this question asked May 26, 2019 at 15:58 user3479267user3479267 23210 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

In a nuxt layout, every page is rendered in place of the <nuxt /> tag.

You are setting the reactive property page in the layout which is mounted only once in the beginning, and all other pages are rendered inside it later. So when a page change occurs the layout doesn't re-mount and the value of page remains the same.

You can add a watcher on the route like this:

<script>
  export default {
    data () {
      return {
        page: this.$route.name
      }
    }
    watch: {
     '$route': function (value) {
       this.page = value.name
      }
    }
  }
</script>  

So, now everytime the route changes, page will updated with the new name of the route.

Use a puted property instead of data, $route is reactive and will trigger a puted update.

puted: {
  page() {
    return this.$route.name
  }  
}

You could also just access $route in your template.

<img v-if="$route.name != 'index'" src="~/assets/img/logo-white.svg">

本文标签: javascriptNuxt Layout update data on every routeStack Overflow