1、父组件获取子组件data数据和子组件方法。
给子组件标签加ref,然后通过this.$refs.childData.方法。

<template>
  <!-- 父组件 -->
  <div>
    <Header ref="childData"></Header>
  </div>
</template>

<script>
import Header from "../../components/header"

export default {
  components:{
    Header
  },
  data() {
    return{

    }
  },
  mounted(){
    this.initData()
    this.initFun()
  },  
  methods:{
    // 获取子组件中data的数据
    initData(){
      console.log(this.$refs["childData"].childrenData)
    },

    // 获取子组件中的方法
    initFun(){
      this.$refs.childData.handeCon()
    }
  }
}
</script>
<template>
  <!-- 子组件 -->
  <div class="header">
    <ul>
      <li v-for="(item,index) in list" :key="index">{{item}}</li>
    </ul>
  </div>
</template>

<script>
export default{
  name:"Header",
  data() {
    return {
       list:["首页","沸点","课程","直播","活动"],
       childrenData: "我是子组件data中的数据"
    };
  },
  mounted(){
    this.handeCon()
  },
  methods:{
    handeCon(){
      console.log("我是子组件中的方法")
    }
  }
}
</script>

<style scoped>
	li{list-style: none;}
	
	ul{
	  display: flex;
	  justify-content: space-between;
	  width: 1200px;
	  margin: 0 auto;
	}

</style>

2、子组件获取父组件data数据和子组件方法。
子组件通过this.$parent.方法获取

<template>
  <!-- 父组件 -->
  <div class="box" style="margin:20px">
    <child ref="childData"></child>
  </div>
</template>
<script>
import Header from "../../components/header"
export default {
  components: {
    child,
  },
  data() {
    return {
      str: {
        name: "猪小凡",
        age: 18,
        title: "父组件数据",
      },
    };
  },
  created() {
  },
  methods: {
    handelAA() {
      alert("我是父组件方法");
    },
  },
};
</script>
<template>
  <!-- 子组件 -->
  <div class="box">
    <button @click="handelFuZuJian">点击</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
    };
  },
  created() {
    this.getListDara();
  },
  methods: {
    getListDara() {
      console.log(this.$parent.str, "str");
    },
    handelFuZuJian() {
      this.$parent.handelAA();
    },
  },
};
</script>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐