首页 > 解决方案 > this.$root 在组件中是什么意思?

问题描述

我有一个主要的 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.$rootApp.vue 组件(因为 App.vue 是所有组件的父级)。是this.$root.children这个 App.vue 组件的子组件,这意味着所有其他组件都将在this.$root.children数组中吗?

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

标签: vue.jsvuejs2vue-componentvue-router

解决方案


这个.$root

this.$root.children

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

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

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

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

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


推荐阅读