自学Vue必看的父子组件访问方式

父子组件访问

有时候我们需要父组件直接访问子组件、子组件直接访问父组件

父组件访问子组件

父组件访问子组件有两种方式,第一种方式是使用 $children,第二种方式是使用 $refs

使用$children(不常使用)

使用 $children拿到所有的子组件
使用 $children访问:this.$children是一个数组类型,它包含所有子组件对象

$children使用方法

注意事项:
(1)使用 this.$children得到的是一个拥有所有子组件的数组类型
(2)单个子组件时可以调用子组件的数据、方法等等
(3)重要部分标有注释

<body>
  //<!-- 父组件模板 -->
<div id="app">
  <cpn></cpn>
  <cpn></cpn>
  <cpn></cpn>
  <button @click="btn">点我</button>
</div>

//<!-- 子组件模板 -->
  <template id="cpn">
    <div>
      <h2>我是子组件</h2>
    </div>
  </template> 


<script src="../vue.js"></script>
<script>
  const app = new Vue({
    el:'#app',
    data:{
      message:"hello vue"
    },
    methods:{
    //使用方法:
      btn() {
        console.log( this.$children);
        for(let child of this.$children){
          console.log(child.message);
          child.show();      
        }        
      }
    },
    //子组件
    components:{
      cpn:{
        template:"#cpn",
        data() {
          return {
            message:"我是子组件的message"
          }
        },
        methods:{
          show() {
            console.log("show"); 
          }
        } 
      }
    }
  })
</script>
</body>

在这里插入图片描述

使用$refs(经常使用)

使用 $refs拿到某一个子组件

$refs使用方法

注意事项:
(1)$refs 是一个对象类型,组件中没有ref属性时默认是一个空的对象
(2)以下代码于上部分代码大部分相同,这里只展示修改部分

  //<!-- 父组件模板 -->
<div id="app">
  <cpn></cpn>
  <cpn></cpn>
  //更改
  <cpn ref="a"></cpn>
  <button @click="btn">点我</button>
</div>
 methods:{
      btn() {
 		//更改
        console.log(this.$refs);
        console.log(this.$refs.a);
        console.log(this.$refs.a.message);               
      }
    },

在这里插入图片描述

子组件访问父组件和根组件(使用较少)

子组件访问父组件使用 $parent,访问根组件使用 $root
主要看Javascript部分代码,以注释标记处为重点

<body>
  //<!-- 父组件模板 -->
<div id="app">
  <cpn></cpn>
</div>

//<!-- 子组件模板 -->
  <template id="cpn">
    <div>
      <h2>我是子组件</h2>
      <button @click="btn">点我</button>
    </div>
  </template> 


<script src="../vue.js"></script>
<script>
  const app = new Vue({
    el:'#app',
    data:{
      message:"我是Vue实例"
    },
    components:{
      cpn:{
        template:"#cpn",
        methods:{
          btn() {
            //访问父组件
            console.log(this.$parent);
            console.log(this.$parent.message);
            //访问根组件
            console.log("我是根组件");
            console.log(this.$root);                      
          }
        } 
      }
    }
  })
</script>
</body>

在这里插入图片描述

发布了61 篇原创文章 · 获赞 58 · 访问量 4015

猜你喜欢

转载自blog.csdn.net/qq_45473786/article/details/105226665