【Vue】vue父子组件通信

1. 父组件向子组件传递

  • 父组件代码
<template>
  <div id="app">
    <h1>This is Parent component</h1> 
    <Child :parent-word='msg'></Child>
  </div>
</template>

<script>
import Child from "./components/Child.vue";
export default {
  name: "parent",
  data() {
    return {
      msg: "Hello,my son"
    };
  },
  components: {
    Child
  }
};
</script>


  • 子组件代码
<template>
  <div>
    I'm Child component.
    <p>parent's word:{{parentWord}}</p>
  </div>
</template>

<script>
export default {
  name: "son",
  props: ["parent-word"],
  data() {
    return {
      msg: "Hello,my son"
    };
  }
};
</script>

  • 以上实现从父组件传递parentWord的消息到子组件,子组件接收并显示
  • 这里需要注意如果是驼峰写法的变量的话,在传递的时候要使用-连接,如:parent-word,在子组件生命注册的时候也是使用parent-word,使用的时候可以使用驼峰写法

2. 子组件像父组件传递

  • 父组件代码
<template>
  <div id="app">
    <h1>This is Parent component</h1> 
    <Child  @childEvent='listentToChild'></Child>
    <p>child's word:{{childWord}}</p>
  </div>
</template>

<script>
import Child from "./components/Child.vue";
export default {
  name: "parent",
  data() {
    return {
      childWord: ""
    };
  },
  components: {
    Child
  },
  methods: {
    //接收子组件传递过来的信息并显示
    listentToChild(data) {
      this.childWord = data;
    }
  }
};
</script>

<style>
</style>

  • 子组件代码
<template>
  <div>
    I'm Child component.
    <button @click="greet">问候爹地</button>
  </div>
</template>

<script>
export default {
  name: "son",
  methods:{
    //点击按钮发送消息给父组件
    greet(){
      this.$emit("childEvent",'Hello!Mammy')
    }
  }
};
</script>

``

- 父组件通过@childEvent='listentToChild'注册一个方法监听子组件传递过来的消息
- 子组件通过 this.$emit("childEvent",'Hello!Mammy')方法向父组件传递消息。this.$emit中的第一个参数正是@childEvent='listentToChild'中的childEvent



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值