Vue之父子组件通信(一)

1:父组件向子组件传递数据

父组件向子组件传值:

1:父组件调用子组件的时候 绑定动态属性

<v-header :title='title'></v-header>

2:在子组件中通过props接受父组件传过来的数据

可以将数据 方法   或则 整个父组件实例 传给子组件

props:['title','msg','run','home']

父组件:

<template>
    <div>
        <!-- 所有内容都要被根节点包含 -->
        <!--父组件通过props向子组件传递数据和方法,就在子组件上绑定相关属性-->
        <v-header :title='title' ::run='run' :home='this'></v-header>
        <br>
        <h2>这是一个首页组件</h2>
        <hr>

    </div>
</template>
<script>
import Header from './Header'
export default {
    components:{
        'v-header':Header
    },
    data(){
        return{
            title:'当前位置'
        }
    },
methods:{
    run(msg){
        alert(this.title+msg)
    ]
}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>

子组件:
<template>
    <div>
<!--    子组件接收父组件传递过来的数据-->
        <h1>这是头部组件--{{title}}</h1>
         <button @click="run('123')">执行父组件传过来的方法,并向父组件传递参数</button>
               <button @click="getParent()">获取父组件的数据和方法</button>
    </div>
</template>
<script>
export default {
    data(){
        msg:'m,sh'
    },
     methods:{
         getParent(){
             alert(this.title)
             alert(this.home.msg)
                //执行父组件中的run方法
             this.home.run()
         }
     },
    props:['title','run','home']//方式一
    props:{//方式二       父向子传值,子组件可以对数据类型进行验证
        'title':String
    }
}
</script>

<style lang="scss" scoped>
h1{
    color: skyblue;
}
</style>

这种方式就是父组件向子组件传值以及传递方法和整个实例的过程

猜你喜欢

转载自blog.csdn.net/W2457307263/article/details/88052677