vue3 父子组件传值详解

小天天天天    前端    999+ 次    2022-09-29 00:01:14


这篇文章主要为大家介绍了vue的父子组件传值,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

现在距离vue3的诞生已经过了很长时间了,笔者也是近期才开始学习vue3。对比vue2来看,vue3在写法发生了不小的变化,最典型的例子就是vue3通过ref,或者reactive实现数据的响应式。因为ref和reactive的出现,使得vue3中父子组件的传值方式也发生了变化

咱们先看下vue2中的写法:

vue2父组件:

<!-- 父组件 -->
<template>
  <div>
    <children :title="title" @getChildren="getChildren"></children>
    <div>子组件说: {{ childrenAsk }}</div>
  </div>
</template>
  
<script>
  import children from "./children.vue"
  export default {
    data() {
      return {
        title: "我是父组件传过来的值",
        childrenAsk: ""
      }
    },
    methods: {
      getChildren(val) {
        this.childrenAsk = val
      }
    }
  }
</script>

vue2子组件:

<!-- 子组件 -->
<template>
  <div>
    <div>父组件传过来的值: {{ title }}</div>
    <button @click="askToFather">点击发送给父组件</button>
  </div>
</template>
<script>
  export default {
    props: {
      title: {
        type: String
      }
    },
    data() {
      return {
        askMsg: "这是我给父组件说的话"
      }
    },
    methods: {
      askToFather() {
        this.$emit("getChildren", this.askMsg)
      }
    }
  }
</script>

在vue2中,子组件向父组件传值通过this.$emit的形式实现,但是vue3中,是不存在this的,vue3中将数据和函数都封装在了setup中,那么vue3是怎么实现的呢?

我们知道vue3中的setup接收两个参数,第一个参数是props,即父组件向子组件传递的props值,第二个值为context,这个值代表了当前的上下文对象,知道这个东西以后现在来实现vue3的父子组件传值

vue3中父传子和vue2中的父传子一样,再次不做过多阐述,下面重点关注的是vue3的子传父

vue3中的子传父写法:

vue3父组件:

<template>
  <div style="color: aqua">父组件</div>
  <div>子组件对我说:{{ children_msg }}</div>
  <children :title="msg" @listen="listenToChildren"></children>
  {{ value }}
</template>
<script lang="ts">
import children from "@/views/component_emit/children.vue"
import { defineComponent, ref } from "vue"
export default defineComponent({
  components: {
    children,
  },
  name: "father",
  setup() {
    let msg = "我是父组件"
    let children_msg = ref("") // ref的作用是实现响应式, 如果没有ref则不能实现响应式(引用数据类型用reactive)
    let listenToChildren = (val) => {
      children_msg.value = val // 使用ref包裹的数据,需要通过.value的形式访问他的值
    }
    return {
      msg,
      children_msg,
      listenToChildren,
    }
  },
})
</script>
<style></style>

vue3子组件:

<template>
  <div style="color: brown">子组件</div>
  <!-- 父传子使用方法和vue2相同 -->
  <div>父组件传过来的值为:{{ title }}</div>
  <button @click="sayToFather">向父组件说话</button>
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
  name: "children",
  props: {
    title: {
      type: String,
    },
  },
  setup(props, context) {
    // context作用是获取上下文对象,
    // 如果setup写法为setup(props, { emit })的方式的话,下面的context可以省略
    const sayToFather = () => {
      const ask = "我是子组件,我对父组件说话"
      context.emit("listen", ask)
    }
    return {
      sayToFather,
    }
  },
})
</script>
<style></style>

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注程序猴的更多内容!


如果你觉得本篇文章对您有帮助,请打赏作者

上一篇: Git提交时自动检测PHP文件是否有语法错误

下一篇: js模拟各种按键操作

最新评论

暂无评论

热门文章

最新评论

网站数据

网站文章数:481

今日UV/PV/IP:7/7/7

昨日UV/PV/IP:18/19 /18

TOP