百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

vue组件间参数、点击事件等方法传递的写法

liuian 2024-12-31 12:58 36 浏览

不管是套用多少层的组件,它的参数传递都是相通的。

如果是父组件往子组件里传递参数,就用属性进行传递,如果是点击操作,就是emit方法传递。当子组件的点击,传递的内容是自身的组件里的内容,不涉及父组件的内容,就无需使用emit方法,直接在子组件里提交数据即可。

创建子组件Form文件夹,里面有两个子组件index.vue和input.vue:

components/Tweet/Form/Input.vue

<template>
  <div>
    <div class="flex items-center flex-shrink-0 p-4 pb-0">
      <div class="flex w-12 items-start">
        <UAvatar :src="user?.profileImage" />
      </div>
      <div class="w-full p-2">
        <UTextarea v-model="text" />
      </div>
    </div>
    <UButton label="发布" @click="handleFormSubmit" />
  </div>
</template>

<script setup lang="ts">
const { postTweet } = useTweets();
/**
 * 属性
 */
type Props = { user: any };

defineProps<Props>();

const text = ref('');

// const emit = defineEmits<{ (e: 'submit', data: any): void }>();
const emit = defineEmits(['onSubmit']);
async function handleFormSubmit() {
  //   emit('onSubmit', {
  //     text: text.value,
  //   });
  //   alert(JSON.stringify({text:text.value}));

  try {
    const response = await postTweet({ text: text.value });
    console.log(response);
  } catch (error) {
    console.log(error);
  }
}
</script>

components/Tweet/Form/index.vue

<template>
  <div>
    <TweetFormInput :user="user"  />
  </div>
</template>

<script setup lang="ts">
const { postTweet } = useTweets();
/**
 * 属性
 */
type Props = { user: any };

defineProps<Props>();

async function handleFormSubmit(formData: any) {
  // 提交表单
  try {
    const response = await postTweet(formData);
    console.log(response);
  } catch (error) {
    console.log(error);
  }
}
</script>

然后就是Form里的index.vue组件添加到页面里,调用这个组件。因为子组件input.vue里,就是一个输入文本框,加上图形和按钮:

图像是当前登录用户的属性里面的profileImage的值,需要设置成属性,传递到外面,最终由页面里获取user的值,传递到组件index.vue,再传递给子组件input.vue里。

pages/index.vue

<template>
  <div :class="['font-normal', { 'bg-black text-white': false }]">
    <div v-if="isAuthLoading">
      <AppLoadingPage />
    </div>
    <!-- main -->
    <div v-else-if="user">
      <MainSection>
        <TweetForm :user="user" />
      </MainSection>
    </div>

    <!-- 登录页面 -->
    <div v-else>
      <AppAuthPage />
    </div>
  </div>
</template>

<script setup lang="ts">
useHead({
  title: '首页',
});
/**
 * user
 * 判断是否从后台获取用户信息
 * 如果没有,则显示登录页面
 * useAuthUser
 */
const { useAuthUser, initAuth, useAuthLoading } = useAuth();

const user = useAuthUser();
const isAuthLoading = useAuthLoading();
onBeforeMount(() => {
  initAuth();
});
</script>
<style lang="postcss" scoped>
.center-box {
  @apply flex items-center justify-center;
}
.tt {
  animation: mask 12s ease infinite forwards;
}
</style>

当然,也可以在子组件input.vue里获取user的值,就不需要添加属性了,直接赋值操作。

当点击按钮提交时,即可存储到数据库当中去:

添加到数据库的方法,直接写在composables方法组件里:

composables/useFetchApi.ts

export default (
  url: string,
  options: {
    headers?: Record<string, string>;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    body?: any;
  } = {},
) => {
  const { useAuthToken } = useAuth();
  return $fetch(url, {
    ...options,
    headers: {
      ...(options.headers || {}),
      Authorization: `Bearer ${useAuthToken().value}`,
    },
  });
};

composables/useTweets.ts

export default () => {
  const postTweet = (formData: any) => {
    const form = new FormData();
    form.append('text', formData.text);

    return useFetchApi('/api/user/tweets', {
      method: 'POST',
      body: form,
    });
  };

  return {
    postTweet,
  };
};

相关推荐

Python 中 必须掌握的 20 个核心函数——items()函数

items()是Python字典对象的方法,用于返回字典中所有键值对的视图对象。它提供了对字典完整内容的高效访问和操作。一、items()的基本用法1.1方法签名dict.items()返回:字典键...

Python字典:键值对的艺术_python字典的用法

字典(dict)是Python的核心数据结构之一,与列表同属可变序列,但采用完全不同的存储方式:定义方式:使用花括号{}(列表使用方括号[])存储结构:以键值对(key-valuepair)...

python字典中如何添加键值对_python怎么往字典里添加键

添加键值对首先定义一个空字典1>>>dic={}直接对字典中不存在的key进行赋值来添加123>>>dic['name']='zhangsan'>>...

Spring Boot @ConfigurationProperties 详解与 Nacos 配置中心集成

本文将深入探讨SpringBoot中@ConfigurationProperties的详细用法,包括其语法细节、类型转换、复合类型处理、数据校验,以及与Nacos配置中心的集成方式。通过...

Dubbo概述_dubbo工作原理和机制

什么是RPCRPC是RemoteProcedureCall的缩写翻译为:远程过程调用目标是为了实现两台(多台)计算机\服务器,互相调用方法\通信的解决方案RPC的概念主要定义了两部分内容序列化协...

再见 Feign!推荐一款微服务间调用神器,跟 SpringCloud 绝配

在微服务项目中,如果我们想实现服务间调用,一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit,配合SpringBoot非常好用!其实Retrofit不仅支持普通的HTTP调用,还能...

SpringGateway 网关_spring 网关的作用

奈非框架简介早期(2020年前)奈非提供的微服务组件和框架受到了很多开发者的欢迎这些框架和SpringCloudAlibaba的对应关系我们要知道Nacos对应Eureka都是注册中心Dubbo...

Sentinel 限流详解-Sentinel与OpenFeign服务熔断那些事

SentinelResource我们使用到过这个注解,我们需要了解的是其中两个属性:value:资源名称,必填且唯一。@SentinelResource(value="test/get&#...

超详细MPLS学习指南 手把手带你实现IP与二层网络的无缝融合

大家晚上好,我是小老虎,今天的文章有点长,但是都是干货,耐心看下去,不会让你失望的哦!随着ASIC技术的发展,路由查找速度已经不是阻碍网络发展的瓶颈。这使得MPLS在提高转发速度方面不再具备明显的优势...

Cisco 尝试配置MPLS-V.P.N从开始到放弃

本人第一次接触这个协议,所以打算分两篇进行学习和记录,本文枯燥预警,配置命令在下一篇全为定义,其也是算我毕业设计的一个小挑战。新概念重点备注为什么选择该协议IPSecVPN都属于传统VPN传统VP...

MFC -- 网络通信编程_mfc编程教程

要买东西的时候,店家常常说,你要是真心买的,还能给你便宜,你看真心就是不怎么值钱。。。----网易云热评一、创建服务端1、新建一个控制台应用程序,添加源文件server2、添加代码框架#includ...

35W快充?2TB存储?iPhone14爆料汇总,不要再漫天吹15了

iPhone14都还没发布,关于iPhone15的消息却已经漫天飞,故加紧整理了关于iPhone14目前已爆出的消息。本文将从机型、刘海、屏幕、存储、芯片、拍照、信号、机身材质、充电口、快充、配色、价...

SpringCloud Alibaba(四) - Nacos 配置中心

1、环境搭建1.1依赖<!--nacos注册中心注解@EnableDiscoveryClient--><dependency><groupI...

Nacos注册中心最全详解(图文全面总结)

Nacos注册中心是微服务的核心组件,也是大厂经常考察的内容,下面我就重点来详解Nacos注册中心@mikechen本篇已收于mikechen原创超30万字《阿里架构师进阶专题合集》里面。微服务注册中...

网络技术领域端口号备忘录,受益匪浅 !

你好,这里是网络技术联盟站,我是瑞哥。网络端口是计算机网络中用于区分不同应用程序和服务的标识符。每个端口号都是一个16位的数字,范围从0到65535。网络端口的主要功能是帮助网络设备(如计算机和服务器...