vue 子组件向父组件传参,子组件调用父组件方法和获取其属性(主动获取父组件的数据和方法)

1.子组件通过$emit 向父组件传参

1.1.子组件:

<template>
  <div class="content">
    <h2>我是子组件</h2>
    <div>
      <button @click.prevent="child_fun('我是子组件传递到父组件的数据')">调用父组件的方法</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
    }
  },
  methods: {
    child_fun(data) {
      //1.childFun是在父组件on监听的方法
      //2.data 是子组件传递给父组件的参数
      this.$emit('childFun', data);
    }
  }
}

</script>
<style>
.content {
  border: 1px solid #999;
  margin: 50px;
}
</style>
<style scope>
.content {
  padding: 50px;
}
</style>


1.2.父组件

<template>
  <div class="content">
    <h2>我是父组件:</h2>
    <div>
      {{fromChild}}
      // 这里是 v-on绑定一个方法 不能缩写成 “:” :是绑定属性
      <Child1 v-on:childFun="child_Fun"></Child1>
    </div>
  </div>
</template>
<script>
// 1.引入子组件
import Child1 from "@/components/Child1"
export default {
  data() {
    return {
      fromChild: ''
    }
  },
  // 2.在父组件中注册
  components: {
    Child1
  },
  methods: {
    child_Fun(data) {
      this.fromChild = data;
    }
  }
}
</script>
<style scoped>
</style>

这里是 v-on绑定一个方法 不能缩写成 “:” :是绑定属性。可缩写成@

vue 子组件向父组件传参,子组件调用父组件方法和获取其属性(主动获取父组件的数据和方法)

2.在子组件中用$parent.调用父组件的方法或获得其数据

在子组件里面通过

this.$parent.属性

this.$parent.方法

2.1父组件:

<template>
  <div class="content">
    <h2>我是父组件:</h2>
    <div>
      <Child></Child>
    </div>
  </div>
</template>
<script>
// 1.引入子组件
import Child from "@/components/Child"
export default {
  data() {
    return {
      parementMsg: '',
      het: 'hellow $parent'
    }
  },
  // 2.在父组件中注册
  components: {
    Child
  },
  methods: {
    parentAlert(data) {
      alert(data)
    }
  }
}
</script>
<style scoped>
</style>

2.2子组件:

<template>
  <div class="content">
    <h2>我是子组件</h2>
    <div>
      <h3>调用父组件的属性:</h3>
      {{this.$parent.het}}
    </div>
    <div>
      <button @click.prevent="getParent_fun('123')">调用父组件的方法</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
    }
  },
  methods: {
    getParent_fun(data) {
      this.$parent.parentAlert(data);
    }
  }
}

</script>
<style>
.content {
  border: 1px solid #999;
  margin: 50px;
}
</style>
<style scope>
.content {
  padding: 50px;
}
</style>


vue 子组件向父组件传参,子组件调用父组件方法和获取其属性(主动获取父组件的数据和方法)