美文网首页
vue 父子组件通讯

vue 父子组件通讯

作者: 阿木心 | 来源:发表于2018-11-07 16:41 被阅读6次

父子组件通讯总结为 “ 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

相关文章

网友评论

      本文标题:vue 父子组件通讯

      本文链接:https://www.haomeiwen.com/subject/lsvvxqtx.html