vue中$root访问根组件、$parent和$emit访问父组件、$ref访问子组件

一、$root 访问根组件中的属性或方法

  • 注意:是根组件,不是父组件。$root只对根组件有用。
this.$root.genMethod();//genMethod()是根组件中的方法名
this.$root.genName;//genName是根组件data中的属性名
  • 完整示例:
<!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()//111
                console.log(this.$root.rootInfo)//我是根元素的属性
              }
            }
          }
        }
      }
    });
  </script>
</body>
</html>

二、$parent$emit 访问父组件中的属性或方法

  1. $parent方法,【推荐】
this.$parent.fatherMethod();//fatherMethod()是父组件中的方法名
this.$parent.fatherName();//fatherName()是父组件data中的属性名
  1. $emit方法。【只能访问父组件中的方法,不能访问父组件中的属性】
<!-- 父组件代码,渲染子组件 -->
<Child  @setValue="valueFn" />
<script>
export default{
  method:{
    valueFn(value) {}
  }
}
</script>

<!-- 子组件代码 -->
<script>
this.$emit('setValue', '参数')
</script>

三、$ref 访问子组件中的属性或方法

<Child ref="fun"/>
<script>
  this.$refs.fun.childMethod(); //childMethod()是子组件中的方法名
  this.$refs.fun.childName; //childName()是子组件中的方法名
</script>
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值