Vue父子组件通信之子组件主动获取父组件的数据和方法(三)

子组件主动获取父组件的数据和方法

实现方式:

this.$parent.属性

this.$parent.方法

代码示例:

父组件

<template>
    <div>
        <!-- 所有内容都要被根节点包含 -->
        <v-header ref='header' :title="title"></v-header>
        <br>
        <h2>这是一个首页组件</h2>
        <hr>

    </div>
</template>
<script>
import Header from './Header'
export default {
    components:{
        'v-header':Header
    },
    data(){
        return{
            msg:'Yes, a first Page!',
            title:'我是的数据NO.1'
        }
    },
    methods:{
        run(){
           alert('我ishi父组件的方法!!!!')
       }   
}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>

子组件:

<template>
    <div>
        <h1>这是头部组件--{{title}}</h1>
        <button @click="getParent()">子组件主动获取父组件的数据和方法</button>
    </div>
</template>
<script>
/* 
    子组件主动获取父组件的数据和方法
    this.$parent.属性
    this.$parent.方法
*/
export default {
    data(){
       return{
            aaa:'m,sh'
       }
    },
     methods:{
       
       getParent(){
          alert( this.$parent.title)
           this.$parent.run()
           
       }
     },
     props:['title']
  
}
</script>

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

到此常见的父子组件通信大概就是这些,欢迎有更好想法或建议的道友留言!!!

Vue之父子组件通信(一)

Vue父子组件通信之父组件主动获取子组件的数据和方法(二)

猜你喜欢

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