Vue之父子间的数据传递(props,$emit())

父组件可以使用 props 把数据传给子组件

  • 在父组件的 script 标签中使用 import 引入 子组件,并在 components 中注册
  • 将子组件标签放在父组件的 template 里,并使用 v-bind:number = "n"的方式动态绑定(v-bind可以简写为:)
  • 在子组件中定义 props:['number'],并使用{{ number }},将父组件传送过来的数据展示在子组件中

代码示例

父组件

<template>
  <div>
      <p>父组件:{{ n }}</p>
      <Son :number="n"></Son>
  </div>
</template>


<script>
import Son from "@/components/Son";

export default {
  data() {
    return {
      n: 0
    }
  },

  components:{
    Son
  }
}
</script>

子组件

<template>
  <div>
    <p>子组件:{{ number }}</p>

  </div>
</template>


<script>
export default {
  props:['number']
}
</script>


子组件可以使用 $emit 触发父组件的自定义事件

  • 在子组件中添加添加 methods,先在对应方法中写需要执行的操作,例如this.count += 1;
  • 在需要执行的操作写完后使用 this.$emit('numChange', this.count),将需要传送的数据 this.count 以 numChange 自定义事件传送至父组件
  • 在父组件中,template 内子组件标签上添加绑定事件 v-on:numChange="getNewCount,用于绑定父组件中接收处理子组件传送数据的方法,即子组件传来的数据需要经过getNewCount处理
  • 在父组件data中定义countFromSon:0,用于接收子组件传回的值
  • 在method中定义getNewCount函数,用于接收处理从子组件传回的值
  • 最后可以通过{{ countFromSon }}将从子组件传回的值展示在父组件中

代码实例

父组件

<template>
  <div>
    <p>父组件:{{ countFromSon }}</p>
    <Son @numChange="getNewCount"></Son>
  </div>
</template>


<script>
import Son from "@/components/Son";

export default {
  data() {
    return {
      countFromSon: 0
    }
  },

  methods: {
    getNewCount(val) {
      this.countFromSon = val
    }
  },

  components: {
    Son
  }
}
</script>

子组件

<template>
  <div>
    子组件:{{ count }}
    <button @click="add">+1</button>
  </div>
</template>


<script>
export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    add() {
      this.count += 1;
      this.$emit('numChange', this.count)
    }
  }
}
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容