菜单
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue 教程

Vue 首页 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue:为何、如何以及设置 Vue 第一个 SFC 页面 Vue 组件 Vue Props Vue v-for 组件 Vue $emit() Vue Fallthrough Attributes Vue Scoped Styling Vue 本地组件 Vue Slots Vue v-slot Vue Scoped Slots Vue 动态组件 Vue Teleport Vue HTTP 请求 Vue Template Refs Vue 生命周期钩子 Vue Provide/Inject Vue Routing Vue 表单输入 Vue 动画 Vue v-for 动画 Vue Build Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

Vue $root 对象


示例

在子组件中使用 $root 对象,来改变 Vue 应用的根组件中的 'text' 数据属性。

<template>
  <div>
    <h3>Change Text</h3>
    <p>Click the button to toggle the text in the PRE tag of the root component.</p>
    <button v-on:click="this.$root.text='Hello!'">Change text in root</button>
  </div>
</template>
运行示例 »

更多示例请参见下方。


定义和用法

$root 对象代表整个 Vue 应用根组件的 Vue 实例。

$root 对象在根组件中使用时,它仅仅指向该组件本身。

我们可以使用 $root 对象直接从子组件(即使在组件树结构中很深的位置)访问根实例,以调用方法、读取或修改数据属性等。

注意: 建议使用 props/emitprovide/inject 来进行 Vue 组件之间的通信,因为具有这些明确定义的通信方式的代码更容易维护。


更多示例

示例

在子组件中使用 $root 对象,来改变根组件中 <p> 标签的颜色,即使该标签在组件树结构中处于多层以上。

<template>
  <div>
    <h4>Grand Child Component</h4>
    <p>Click the button to toggle the color of the P tag in the root component.</p>
    <button v-on:click="this.$root.color='lightgreen'">Change color in root</button>
  </div>
</template>
运行示例 »

相关页面

Vue 教程:Vue Props

Vue 教程:Vue $emit() Method

Vue 教程:Vue Provide/Inject

Vue Reference: Vue $emit() Method

Vue 参考:Vue $parent 对象


×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持