【问题标题】:what does this.$root means in a component?this.$root 在组件中是什么意思?
【发布时间】:2019-10-07 14:07:12
【问题描述】:

我有一个主要的 App.vue 组件。在那里,我有以下代码:

export default {
  data() {
    return {
      testVariable:false
    }
  },
}
</script>

<template>
  <VApp :dark="testVariable:false"
    <div id="app">
      <RouterView :key="$route.fullPath" />
    </div>
  </VApp>
</template>

然后在其中一个组件中,我有以下代码:

data() {
    return {
      testVariable: this.$root.$children[0].testVariable,
    }
  },

methods: {
    darkModeToggle(e) {
      this.$root.$children[0].testVariable = e
    },
  },

问题 1) this.$root 和 this.$root.children 是什么意思?是this.$root 总是 App.vue 组件(因为 App.vue 是所有组件的父级)。 this.$root.children 是这个 App.vue 组件的子组件,这意味着所有其他组件都将在 this.$root.children 数组中?

问题2)这条线是什么意思?&lt;RouterView :key="$route.fullPath" /&gt;。我的意思是我们为什么要通过:key="$route.fullPath"?

【问题讨论】:

    标签: vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    this.$root

    this.$root.children

    this.$root 总是 App.vue 组件吗?

    • 没有。 App.vue 有一个父组件,它是 main.js 中的 new Vue(...)。所以new Vue(...) 是实际的$root

    this.$root.children 是这个 App.vue 组件的子组件,这意味着所有其他组件都将在 this.$root.children 数组中吗?

    • .children 是直接子组件,而不是后代。在这种情况下,$root 只有 1 个直接子代,即 App.vue

    这条线是什么意思? .我的意思是我们为什么要通过 :key="$route.fullPath"?

    【讨论】:

    • 所以 this.$root 将永远是用 main.js 编写的新 Vue 实例?我从哪个组件中调用它并不重要?
    • 这在 Nuxt 中会不会一样?
    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 2013-01-11
    • 2014-05-20
    • 2011-08-22
    • 1970-01-01
    • 2018-10-29
    • 2011-09-10
    • 2012-05-04
    相关资源
    最近更新 更多