iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >Vue父子组件属性传递实现方法详解
  • 630
分享到

Vue父子组件属性传递实现方法详解

Vue父子组件属性传递Vue属性传递Vue父子组件传递 2023-02-08 12:02:42 630人浏览 独家记忆
摘要

目录前言组件之间属性的传递父组件传递属性给子组件子组件传递属性给父组件前言 这节我们主要从案例出发,用vue3的写法写父子组件之间的属性传递。 组件之间属性的传递 我们定义一个Rat

前言

这节我们主要从案例出发,用vue3的写法写父子组件之间的属性传递。

组件之间属性的传递

我们定义一个Rate组件,具有以下功能:

  • 接收来自外部组件传入的参数,starCount代表星星个数。color代表星星颜色。
  • 需要根据传入星星的个数,展示对应数量的星星。

父组件传递属性给子组件

那么在编写组件的时候,我们需要注意什么?

  • 我们可以使用defineProps来规范传递数据的格式。可以结合withDefaults来进行默认值的赋值。
  • 如果是响应式数据的传递,在传递给子组件的时候,需要添加前缀 :。如果是常量,则不用。

我们在components目录下创建完Rate.ts文件后。完整代码如下:

<template>
  <div :style="fontstyle">
    {{ rate }}
  </div>
</template>
<script setup lang="ts">
import { computed, defineProps, withDefaults } from "Vue";
// 定义父组件传入的参数类型
interface Props {
  starCount: number;
  color: string;
}
// 规定传值类型以及赋上默认值
let props = withDefaults(defineProps<Props>(), {
  starCount: 0,
  color: "blue",
});
// 凡是计算有关的,我们都用computed来包装
const rate = computed(() =>
  "★★★★★☆☆☆☆☆".slice(5 - props.starCount, 10 - props.starCount)
);
const fontstyle = computed(() => {
  return `color:${props.color};`;
});
</script>

外部组件调用如下:

<template>
  <Rate starCount="3"></Rate>
  <Rate starCount="4" color="red"></Rate>
  <Rate starCount="1" color="green"></Rate>
</template>
<script setup>
import Rate from "./components/Rate.vue";
</script>

最终效果如下:

子组件传递属性给父组件

我们在编写组件的时候,我们需要注意什么?

  • 子组件:需要通过defineEmits函数,注册一个自定义事件或者其他事件,例如click事件。然后手动触发emit函数,调用该自定义事件,并传递参数。
  • 父组件:引用子组件的时候,通过v-on绑定一个函数,指向子组件里面定义的事件。注意:v-on的效果等同于@符号。

定义一个子组件Son

<template>
  <div style="margin: 10px; border: 2px solid red">
    我是子组件
    <button @click="transValue" style="margin: 5px;background:#caca88">传值给父组件</button>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
// 定义所要传给父组件的值
const num = ref<number>(0);
// 使用defineEmits注册一个自定义事件
const emit = defineEmits(["getValue"]);
// 点击事件触发emit,去调用我们注册的自定义事件getValue,并传递value参数至父组件
const transValue = () => {
  num.value++;
  emit("getValue", num.value);
};
</script>

父组件Father

<template>
  <div class="fa">
    <div style="margin: 10px;">我是父组件</div>
    父组件接收子组件传的值:{{sonMessage}}
    <Son @getValue="getSonValue"></Son>
    <!-- <Son v-on:getValue="getSonValue"></Son> -->
  </div>
</template>
<script setup lang="ts">
import Son from './Son.vue'
import {ref} from "vue";
const sonMessage = ref<String>('0')
const getSonValue = (value: String) => {
  sonMessage.value = value
}
</script>
<style scoped>
.fa{
  border: 3px solid cornflowerblue;
  width: 400px;
  text-align: center;
}
</style>

运行效果如下:

到此这篇关于Vue父子组件属性传递实现方法详解的文章就介绍到这了,更多相关Vue父子组件属性传递内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Vue父子组件属性传递实现方法详解

本文链接: https://www.lsjlt.com/news/195092.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作