($children,$refs,$parent)的使用

如果项目很大,组件很多,怎么样才能准确的、快速的寻找到我们想要的组件了??

  1. $refs
    首先你的给子组件做标记。demo :<firstchild ref="one"></firstchild>
    然后在父组件中,通过this.$refs.one就可以访问了这个自组件了,包括访问自组件的data里面的数据,调用它的函数
    注意
    ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素; 如果用在子组件上,引用就指向组件实例
    当 v-for 用于元素或组件的时候,引用信息将是包含 DOM 节点或组件实例的数组

  2. $children
      他返回的是一个组件集合,如果你能清楚的知道子组件的顺序,你也可以使用下标来操作;

for(let i=0;i<this.$children.length;i++){
          console.log(this.$children[i].children_data);
          this.$children[i].children_fun();
        }

3.$parent在子组件中调用父组件的方法或获得其数据


parents.vue

<template>
  <div id='parents'>
            <p>我是父组件
              <button @click="click1hanlde">获取子组件1的数据与方法</button>
              <button @click="click2hanlde">获取所有子组件的数据和方法</button></p>
             <children1 ref="children1"></children1>
             <children2 ref="children2"></children2>
  </div>
</template>
<script>
  import children1 from './children1.vue'
  import children2 from './children2.vue'
  export default {
    components:{
      children1, children2
    },
    data() {
      return {
        ParentData:'AAA'
      };
    },
    methods:{
      click1hanlde(){
        console.log(this.$refs.children1.children_data)
        this.$refs.children1.children_fun();
      },
      click2hanlde(){
        for(let i=0;i<this.$children.length;i++){
          console.log(this.$children[i].children_data);
          this.$children[i].children_fun();
        }
      },
      showParentData(){
            console.log(this.ParentData)
      }
    }
  };
</script>

children1.vue

<template>
  <div id='children1'>
          <p>我是子组件1: <button @click="getParent_fun">获取父组件的数据和方法 </button></p>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        children_data:'children_data1',
      };
    },
    methods:{
      children_fun(){
            console.log('我是子组件1的方法')
      },
      getParent_fun(){
        this.$parent.showParentData();
      }
    }
  };
</script>

children2.vue

<template>
  <div id='children2'>
          <p>我是子组件2</p>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        children_data:'children_data2',
      };
    },
    methods:{
      children_fun(){
            console.log('我是子组件2的方法')
      }
    }
  };
</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,163评论 0 29
  • 以下内容是我在学习和研究Vue时,对Vue的特性、重点和注意事项的提取、精练和总结,可以做为Vue特性的字典; 1...
    科研者阅读 14,220评论 3 24
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 3,376评论 0 2
  • (1)byte(字节型) 1字节short(短整型) 2字节int(整型) 4字节long(长整型)8字节f...
    一二三四五丶阅读 315评论 0 0
  • 正午蒸发的汗水,黄昏拉长的影子,夜晚璀璨的霓虹。我开始无时无刻想念你,想念你洗完头发之后脖颈的香味,想念你曾念着要...
    时间新欢阅读 368评论 0 1

友情链接更多精彩内容