Vue 组件

父组件:Index.vue

<template>
  <el-row>
    <el-row>
      <!-- 使用子组件 -->
      <student ref="stuCom" :stu="stu" @callFunction="callFunction"></student>
    </el-row>
    <el-row>
      <el-button @click="getStudent">父组件按钮</el-button>
    </el-row>
  </el-row>
</template>

<script>
// 引用子组件
import student from "../../components/student";
export default {
  // 注册子组件
  components: { student },
  data() {
    return {
      stu: { name: "张三", address: "苏州" },
    };
  },
  methods: {
    // 接收子组件回调,并且接收参数
    callFunction(item) {
      console.log("接收子组件回调,并且接收参数");
      console.log(item);
    },
    getStudent() {
      // 调用子组件方法,并传参
      this.$refs.stuCom.$emit("getStu", "张三");
      // 获取子组件参数
      this.stu = this.$refs.stuCom.item;
      console.log("获取子组件参数");
      console.log(this.stu);
    },
  },
  mounted() {},
};
</script>

<style scoped>
</style>

子组件:student.vue

<template>
  <el-row>
    <!-- item和el控件双向绑定 -->
    <el-input v-model="item.name"></el-input>
    <el-input v-model="item.address"></el-input>
    <el-button @click="callFunc">子组件按钮</el-button>
  </el-row>
</template>

<script>
export default {
  name: "student",
  data() {
    return {
      item: {},
    };
  },
  // 获取父组件传参
  props: {
    stu: { name: "", address: "" },
  },
  // 监听传参,赋值给item
  watch: {
    stu: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        this.item = newVal;
      },
    },
  },
  methods: {
    callFunc() {
      // 调用父组件方法,并传参item
      this.$emit("callFunction", this.item);
    },
    getStu(name) {
      console.log("接收父组件调用,并且接收参数");
      console.log(name);
    },
  },
  mounted() {
    // 监听父组件调用
    this.$nextTick(function () {
      this.$on("getStu", function (name) {
        this.getStu(name);
      });
    });
  },
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值