Vue 中$root 的用法:
$root用法:
作用: 访问跟组件的属性和方法:
$root 只是对跟组件有用, 不是父组件, $root 只是对对跟组件有用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <title>$root访问根组件中的属性或方法</title> </head> <body> <div id="app"> <com1></com1> </div> <script> var vm = new Vue({ el: "#app", data() { return { rootInfo:"我是根元素的属性" } }, methods: { alerts() { alert(111) } }, components: { com1: { data() { return { info: "组件1" } }, template: "<p>{{ info }} <com2></com2></p>", components: { com2: { template: "<p>我是组件1的子组件</p>", created() { this.$root.alerts() console.log(this.$root.rootInfo) } } } } } }); </script> </body> </html>
|
访问父组件的属性或方法 this.$parent;
访问子组件的属性或方法 this.$ref;