如何在 vue.js 中制作动态面包屑?

How make dynamic breadcrumbs in vue.js?

我想要一个基于我在某个类别上单击的位置的动态面包屑,但我收到一条错误消息,指出我的变量未定义:TypeError: Cannot read properties of undefined (reading 'homeMenu')。然而在我的getHomeCategory函数中,homeCategory的console.log显示Perma'Thèque。不懂怎么弄,谢谢

这是代码:

<script>
    export default {
        props: {
        },
        data: () => ({
            homeMenu: "",
            breadcrumbs: [
                {
                    text: 'Accueil',
                    disabled: false,
                    href: '/',
                },
                {
                    text: this.homeMenu,
                    disabled: false,
                    href: "/" + this.homeMenu,
                },
            ],
            
        }),
        computed: {
            ...mapGetters({
                console: () => console,
                homeCategory: 'home/getCategory',    
            })
        },
        methods: {
            getHomeCategory ()  {
                if (this.homeCategory === "Perma'Thèque") {
                    console.log(this.homeCategory)
                    return this.homeMenu = "permatheque"
                } else {
                    return this.homeMenu = "null"
                }
            },

            
        },
        mounted() {
            if (this.plantActive) this.loading = false;
            this.getHomeCategory()
        }
    }
</script>

data()在这里被声明为箭头函数,所以this指的是外层作用域,而不是Vue组件实例,但是这里即使作为常规函数,this.homeMenu也赢了'还存在。

看来你真的希望 breadcrumbshomeMenu 做出反应,所以你应该将 breadcrumbs 移动到 computed prop:

export default {
  data: () => ({
    homeMenu: '',
  }),
  computed: {
    breadcrumbs() {
      return [
        {
          text: 'Accueil',
          disabled: false,
          href: '/',
        },
        {
          text: this.homeMenu,
          disabled: false,
          href: '/' + this.homeMenu,
        },
      ]
    }
  }
}

demo