Vue的props,子节点,获取父节点的数据的一个方式

vue的参数里面有一个props, 它是子节点,获取父节点的数据的一个方式

先看看father.vue,在这里,有一个子节点,是使用自定义的组件child.vue,这个组件的节点名叫Children,里面有一个参数fatherName绑定了name参数,当data()里面的name参数被改变,这里的fatherName会跟着改变,接下来看看child.vue

father.vue

<template>
    <div>
        <!--子节点,这里的fatherName 跟 name做了绑定-->
        <Children :fatherName="name"></Children>
    </div>
</template>

<script>
    import Child from './child.vue'
    export default{
        data(){
          return{
              name:'John'
          }
        },
        components:{
          Children:Child
        }
    }


</script>

在child.vue组件当中,我们定义了一个按钮,点击之后会从父节点中获取fatherName,但这里必须注意的是,必须要引用父节点的参数,这里才会正常获取到,这里就需要用到props,通过在这里定义了与父节点中一直的参数名,自然在这里就能获取到了

child.vue

<template>
    <div>
        <!--测试效果的按钮-->
        <button @click="test()">Test Ref</button>
    </div>
</template>

<script>
    export default{
        props:['fatherName'],
        methods:{
            test(){
                console.log(this.fatherName)
            }
        }
    }

</script>