首页 > 解决方案 > 使用 NuxtJS (VueJS) 设置动态 ActionBar 标题和突变问题

问题描述

通常,使用VueCLI3,我曾经使用属性为ActionBar(例如Vuetify)设置动态标题vue-router meta(静态类型,因为它们是在router.js文件中设置的)

例子:

// router.js

const routes = [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta : {
        title : 'Welcome Home',
      }
    },
]
// in App.vue 
<template>
  <v-app>
    <ActionBar :title="$route.meta.title"></ActionBar>
    <router-view></router-view> 
  </v-app>
</template>

使用Nuxt.JS,我无论如何都找不到要设置route-meta的,所以我使用并在商店中设置标题并在主布局中获取。Vuex.store gettermutations

例子:

// in mainLayout.vue
<template>
  <v-app dark> 
    <v-app-bar app color="primary" dark>
      <v-toolbar-title v-text="actionTitle" />
    </v-app-bar>

    <v-main>
      <v-container>
        <nuxt keep-alive />
      </v-container>
    </v-main>

  </v-app>
</template>

<script>
export default {
  computed: {
    ...mapGetters([
      'actionTitle'
    ])
  },
}
// in some routed page, eg: index.vue
export default {
  created() {
    this.$store.commit('setActionTitle', 'Medical Service BD')
  },
}

当我使用<nuxt keep-alive />或使用缓存组件时会出现问题。此缓存不会提交这些突变,因此操作栏标题保持上一个标题的静态。

哪种方法适合动态标题设置?

标签: javascriptvue.jsnuxt.js

解决方案


我从 reddit 找到的解决方案是使用activated方法。例子:

export default {
  activated() {
    this.$store.commit('setActionTitle', 'Medical Service BD')
  },
}

推荐阅读