组件间通信

父传子
  • Parent.vue
<template>
  <div>
    <h4>父组件--父传子</h4>
    <p>
      v-model 实时修改 text 的值,然后 change 监听到改变就会立马触发该方法获取里面的内容传递给 Text
    </p>
    <input type="text" v-model.lazy="text" @change="ChangeText" />
    <childer :Text="text" />
  </div>
</template>

<script>
import childer from "./childer";
export default {
  name: "App",
  data() {
    return {
      text: "",
    };
  },
  components: {
    childer,
  },
  methods: {
    ChangeText(dataText) {
      this.Text = dataText;
    },
  },
};
</script>

<style></style>

  • 子组件
<template>
  <div class="childer">
    <h5>子组件</h5>
    <div class="childerText">{{ Text }}</div>
  </div>
</template>

<script>
export default {
  name: "childer",
  props: {
    Text: String,
    // default: () => {},
  },
};
</script>

<style lang="scss">
.childer {
  .childerText {
    width: 200px;
    height: 30px;
    border: 1px solid #ccc;
  }
}
</style>

子传父
  • 父组件
<template>
  <div>
    <h3>父组件--子传父</h3>
    <p>定义好修该父组件自己数据的方法,然后传给子组件传参修改</p>
    <div class="parentData">{{ parentData }}</div>
    <childer1 @getData="getData" />
  </div>
</template>

<script>
import childer1 from "./childer1";
export default {
  name: "Parent1",
  data() {
    return {
      parentData: "",
    };
  },
  components: {
    childer1,
  },
  methods: {
    getData(childerData) {
      this.parentData = childerData;
    },
  },
};
</script>

<style lang="scss">
.parentData {
  width: 200px;
  height: 40px;
  border: 1px solid #ccc;
}
</style>

  • 子组件
<template>
  <div>
    <h5>子组件</h5>
    <p>定义一个方法传值给父组件</p>
    <input type="text" v-model="childerText" />
    <button @click="setData">传递到父组件</button>
  </div>
</template>

<script>
export default {
  name: "childer1",
  data() {
    return {
      childerText: "",
    };
  },
  methods: {
    setData() {
      this.$emit("getData", this.childerText);
    },
  },
};
</script>

<style></style>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值