vue 父子组件通讯

父子组件通讯总结为 “ prop 向下传递,emit事件向上传递”。

父组件通过 prop 给子组件下发数据,子组件通过emit事件给父组件发送消息。

1⃣️ 父组件传值给子组件

1.1父组件结构:

<template>
<div>
    <input type="text" v-model="name">
    <children :inputName="name"></children>
</div>
</template>
<script>
// import导入子组件
  import children from './children'
  export default {
    components: {
      children
    },
    data () {
      return {
        name: ""
      }
    }
  }
</script>

1.2子组件结构:

<template>
  <div>
    子组件:
    <span>{{inputName}}</span>
  </div>
</template>
<script>
  export default {
    // 通过props接收父组件的值
    props: {
      inputName: String,
      required: true
    }
  }
</script>
image.png

2⃣️ 子组件传值给父组件

2.1父组件结构

<div>
    <span>{{name}}</span>
    <children v-on:childrenByValue="childrenByValue"></children>
</div>
</template>
<script>
// import导入子组件
  import children from './children'
  export default {
    components: {
      children
    },
    data () {
      return {
        name: ""
      }
    },
    methods:{
      childrenByValue(childValue){
     //childValue 以参数的形式传递
           this.name = childValue;
      }
    }
  }
</script>

2.2子组件结构

<div>
<input type="button" value="点击触发" @click="childrenClick">
</div>
</template>
<script>
  export default {
    data () {
      return {
        childrenValue: "我是子组件的值"
      }
    },
    methods:{
     childrenClick(){
        this.$emit('childrenByValue', this.childrenValue)
      }
    }
  }
</script>
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容