vue学习

父子组件之间的访问

2017-09-16  本文已影响0人  努力努力的老姑娘

---转载keepfool的60分钟组件快速入门(下篇)

父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。针对这几种情况,Vue.js都提供了相应的API:

  1. 父组件访问子组件:$children$refs

$children

在父组件中,通过this.$children可以访问子组件。
this.$children是一个数组,它包含所有子组件的实例。

$refs

<template id="parent-component">
    <child-component1 v-ref:cc1></child-component1>
    <child-component2 v-ref:cc2></child-component2>
    <button v-on:click="showChildComponentData">显示子组件的数据</button>
</template>

在父组件中,则通过$refs.索引ID访问子组件的实例:

showChildComponentData: function() {
    alert(this.$refs.cc1.msg);
    alert(this.$refs.cc2.msg);
}
  1. 子组件访问父组件:$parent
    下面这段代码定义了两个组件:child-component和它的父组件parent-component。在子组件中,通过this.$parent可以访问到父组件的实例。

<div id="app">

<div id="app">
    <parent-component></parent-component>
</div>

<template id="parent-component">
    <child-component></child-component>
</template>

<template id="child-component">
    <h2>This is a child component</h2>
    <button v-on:click="showParentComponentData">显示父组件的数据</button>
</template>

<script src="js/vue.js"></script>
<script>
    Vue.component('parent-component', {
        template: '#parent-component',
        components: {
            'child-component': {
                template: '#child-component',
                methods: {
                    showParentComponentData: function() {
                        alert(this.$parent.msg)
                    }
                }
            }
        },
        data: function() {
            return {
                msg: 'parent component message'
            }
        }
    })
    new Vue({
        el: '#app'
    })
</script>
  1. 子组件访问根组件:$root
上一篇 下一篇

猜你喜欢

热点阅读