美文网首页
VUE进阶 - $parent 和 $children

VUE进阶 - $parent 和 $children

作者: wyc0859 | 来源:发表于2020-04-26 23:57 被阅读0次

    1、ref为子组件指定一个索引名称,通过索引来操作子组件;
    2、this.$parent 可以直接访问该组件的父实例或组件;
    3、父组件也可以通过this.$children 访问它所有的子组件; 需要注意 $children 并不保证顺序,也不是响应式的。

    index.vue
    <template>
    <div>
      <testVue ref="test"></testVue>   
      <testVue2></testVue2> 
      <button @click="clickChild1">$refs方式获取子组件值</button> 
      <button @click="clickChild2">$children方式获取子组件值</button>
    </div>
    </template>
    <script>
    import testVue from './test'
    import testVue2 from './test2'
    export default {
      data(){
        return {
          total: 108
        }
      },
      components: {
        testVue,
        testVue2  
      },
      methods: {
        funa(e){
            console.log("index",e)
        },
        clickChild1(){
          console.log(this.$refs.test.msg);
        },
        clickChild2(){
            console.log(this.$children[0].msg);
            console.log(this.$children[1].msg);
        }
      }
    }
    </script>
    
    test.vue
    <template>
    <div>
      <button @click="parentClick">点击访问父组件</button>
    </div>
    </template>
    <script>
    export default {
      data(){
        return {
          msg:"test1"
        }
      },
      methods: {
        parentClick(){
            this.$parent.funa("xx")
           console.log(this.$parent.total);
        }
      }
    }
    </script>
    
    test2.vue
    <template>
    <div>
    </div>
    </template>
    <script>
    export default {
      data(){
        return {
         msg: 'test2'
        }
      }
    }
    </script>
    

    root 和parent 都能够实现访问父组件的属性和方法,两者的区别在于,如果存在多级子组件,通过parent 访问得到的是它最近一级的父组件,通过root 访问得到的是根父组件

    相关文章

      网友评论

          本文标题:VUE进阶 - $parent 和 $children

          本文链接:https://www.haomeiwen.com/subject/izxewhtx.html