VUE中父组件向子组件传递数据 props使用

VUE中,子组件是不能直接访问父组件的数据(通常来讲,固然若是你要破坏原则也是能够),以下<javascript

<body>
  <
div id="fathercomponent"> <ul> <li v-for="item in fatherdatas">{{item}}</li> <!--父组件能够访问它本身的数据--> </ul> <child-component></child-component> </div>
</body>
<script type="text/javascript">
        Vue.component('child-component', {
           // template:'<ul><li v-for="item in fatherdatas"></li></ul>'//子组件不能访问到父组件的数据
        })
        vm = new Vue({
            data: {
                fatherdatas: [1,2,3,4,5]
            }
        }).$mount('#fathercomponent');
 </script>

上面代码  vm实例挂在了id 为fathercomponent 的DIV中,至关于fathercomponent为一个组件了,这个时候咱们在其中定义了一个另外一个新组件,这个新定义的组件,和原来的组件,即为父子关系,暂且命名为child-componentjava

咱们在vm 中定义的数据 fatherdatas,是父组件fathercomponent中的数据,能够直接在父组件中引用,子组件内部是没法访问到fatherdatas数据的。若是咱们须要访问这个fatherdatas须要经过props属性来实现,具体以下数组

 

    <div id="fathercomponent">
        <ul>
            <li v-for="item in fatherdatas">{{item}}</li> <!--正确父组件能够访问它本身的数据-->
        </ul>
        <child-component :dataarr="fatherdatas"></child-component> <!--咱们将父组件中的fatherdatas数据传给子组件中的dataarr-->
    </div>

 

  Vue.component('child-component', {
            props: ['dataarr'],//给props添加一个属性,这个属性名字是以前在组件标签中加的
            template: '<ul><li v-for="item in dataarr">{{item}}</li></ul>' //这个时候父组件中的fatherdatas 已经传递给了当前组件的dataarr,这样就能够访问了

        })
        vm = new Vue({
            data: {
                fatherdatas: [1,2,3,4,5]
            }
        }).$mount('#fathercomponent');

父组件传递给子组件,是按值传递,由于此时的值是一个对象地址,因此无论是改子组件中的dataarr,仍是改父组件fatherdatas,都会影响到另外一方,以下this

    <div id="fathercomponent">
        <ul>
            <li v-for="item in fatherdatas">{{item}}</li> <!--正确父组件能够访问它本身的数据-->
        </ul>
        <child-component :dataarr="fatherdatas" @father="getfatherdatas"></child-component> <!--咱们将父组件中的fatherdatas数据传给子组件中的dataarr-->
    </div>                                      <!--定义一个father事件-->
        Vue.component('child-component', {
            props: ['dataarr'],//给props添加一个属性,这个属性名字是以前在组件标签中加的
            template: '<ul><li v-for="item in dataarr">{{item}}</li></ul>', //这个时候父组件中的fatherdatas 已经传递给了当前组件的dataarr,这样就能够访问了
            created: function () {
                this.dataarr.push(6);//子组件中的dataarr 添加一个数组元素
                this.$emit('father');//触发组件的father事件
            }

        })
        vm = new Vue({
            methods: {
                getfatherdatas() {
                    console.log(this.fatherdatas.join(','));//输出1,2,3,4,5,6
                }
            },
            data: {
                fatherdatas: [1,2,3,4,5]
            }
        }).$mount('#fathercomponent');