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

VUE中,子组件是不能直接访问父组件的数据(一般来说,当然如果你要破坏原则也是可以),如下<

<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-component

我们在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,都会影响到另一方,如下

    <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');
原文地址:https://www.cnblogs.com/fuyun2000/p/10676406.html