vue父子组件传值 vue3 父子组件传值详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue父子组件传值 vue3 父子组件传值详解

淮北才子   2021-11-16 我要评论
想了解vue3 父子组件传值详解的相关内容吗,淮北才子在本文为您仔细讲解vue父子组件传值的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:vue父子组件,vue传值,下面大家一起来学习吧。

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

咱们先看下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>

子组件:

<!-- 子组件 -->
<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的子传父

父组件

<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>

子组件:

<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>

总结

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们