Vue3<script setup>语法糖下,实现父子组件通信以及数据监听的三种方法。

news2024/7/6 17:38:30

在Vue3的script setup语法糖中,没有办法通过Vue2的ref、props、parent、中央时间总线等等众多方法,通过this指针简单的实现父子组件的通信,网络上也很少有关于script setup语法糖的相关教程,所以决定自己写一个详细教程,方便以后学习查看并记录。
在这里插入图片描述

一、通过defineProps()和watch()方法实现父子组件通信以及数据监听。

1.父组件代码实例:props传值

<script setup>
import { ref } from 'vue';
import { get_article_cates } from "@/api/api.js";
import Article from "./article/index.vue";
const cate_list=ref([]);
const active = ref(0)
const Cates=()=>{
    get_article_cates().then((res) => {
        cate_list.value=res.data.data;
    }).catch((err) => {
        console.log(err)
    })
}
Cates();
const cates_id=ref();
const go_cates=(data)=>{
    cates_id.value=data.id;
};

</script>

<template>
    <div class="hu_box">
        <var-tabs v-model:active="active" color="rgba(255, 255, 255, 0.35)" active-color="#1e131d" inactive-color="#36292f" class="hu_tab">
            <var-tab v-for="(item,index) in cate_list" @click="go_cates(item)">{{item.name}}</var-tab>
        </var-tabs>
        <div class="hu_index">
            <Article :cates_id="cates_id" />
        </div>
    </div>
</template>

2.子组件代码实例:defineProps()方法获取父组件的值,watch()方法监听props的值

<script setup>
import { ref, watch } from 'vue';
import { post_articles_list,get_article_details } from "@/api/api.js";
const Art_list=ref([]);

//子组件相关方法
let query={
    classifyID: '',
    page: 1,
    pagesize: 5 
}
const Articles_list=()=>{
    post_articles_list(query).then((res) => {
        Art_list.value=res.data.data;
    }).catch((err) => {
        console.log(err)
    });
}

//通信部分方法
//传入props数据
const props = defineProps({
    cates_id: String
})
if (props.cates_id==undefined) {
    Articles_list();
}
//数据监听
watch(() => props.cates_id, (newValue, oldValue) => {
  query.classifyID=newValue;
  Articles_list();
},{ deep: true });
</script>

<template>
    <div class="hu_article">
        <div class="hu_son_box" v-for="(item,index) in Art_list" :key="index" @click="go_router(item.Id)">
            <div>{{ item.title }}</div>
            <div>{{ item.pub_date }}</div>
        </div>
    </div>
</template>

二、通过defineProps()、watch()、ref()、defineExpose()方法实现父子组件通信以及数据监听。

1.父组件代码实例:props传值、ref执行子组件方法

<script setup>
import { ref } from 'vue';
import { get_article_cates } from "@/api/api.js";
import Article from "./article/index.vue";
const cate_list=ref([]);
const active = ref(0)
const Cates=()=>{
    get_article_cates().then((res) => {
        cate_list.value=res.data.data;
    }).catch((err) => {
        console.log(err)
    })
}
Cates();
const cates_id=ref();
const Son_subassembly = ref();
const go_cates=(data)=>{
    cates_id.value=data.id;
    if (Son_subassembly.value) {
        Son_subassembly.value?.Articles_list();
    }
};

</script>

<template>
    <div class="hu_box">
        <var-tabs v-model:active="active" color="rgba(255, 255, 255, 0.35)" active-color="#1e131d" inactive-color="#36292f" class="hu_tab">
            <var-tab v-for="(item,index) in cate_list" @click="go_cates(item)">{{item.name}}</var-tab>
        </var-tabs>
        <div class="hu_index">
            <Article :cates_id="cates_id" ref="Son_subassembly"/>
        </div>
    </div>
</template>

2.子组件代码实例:defineProps()方法获取父组件的值,watch()方法监听props的值,defineExpose()暴露出子组件属性。

<script setup>
import { ref, watch } from 'vue';
import { post_articles_list,get_article_details } from "@/api/api.js";
const Art_list=ref([]);

//子组件相关方法
let query={
    classifyID: '',
    page: 1,
    pagesize: 5 
}
const Articles_list=()=>{
    post_articles_list(query).then((res) => {
        Art_list.value=res.data.data;
    }).catch((err) => {
        console.log(err)
    });
}

//通信部分方法
//传入props数据
const props = defineProps({
    cates_id: String
})
if (props.cates_id==undefined) {
    Articles_list();
}
//数据监听
watch(() => props.cates_id, (newValue, oldValue) => {
  query.classifyID=newValue;
},{ deep: true });
//子组件实例暴露出属性:defineExpose
defineExpose({
    Articles_list
})
</script>

<template>
    <div class="hu_article">
        <div class="hu_son_box" v-for="(item,index) in Art_list" :key="index" @click="go_router(item.Id)">
            <div>{{ item.title }}</div>
            <div>{{ item.pub_date }}</div>
        </div>
    </div>
</template>

三、通过defineExpose()和pinia实现父子组件通信以及数据监听。

1.安装pinia,新建stores文件夹,下面新建counter.js

安装pinia
npm install pinia
stores文件夹下新建counter.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter',  {
  state: () => {
    return {
      Central_data: '',
    }
  },
  persist: true,
})

2.父组件代码实例:pinia传值、ref执行子组件方法

<script setup>
import { ref } from 'vue';
import { get_article_cates } from "@/api/api.js";
import Article from "./article/index.vue";

//pinia通信测试
import { useCounterStore } from "@/stores/counter.js";
const store = useCounterStore();

const cate_list=ref([]);
const active = ref(0)
const Cates=()=>{
    get_article_cates().then((res) => {
        cate_list.value=res.data.data;
    }).catch((err) => {
        console.log(err)
    })
}
Cates();
const cates_id=ref();
const Son_subassembly = ref();
const go_cates=(data)=>{
	cates_id.value=data.id;
    //pinia数据通信测试测试
    store.Central_data=data.id;
    if (Son_subassembly.value) {
        Son_subassembly.value?.Articles_list();
    }
};

</script>

<template>
    <div class="hu_box">
        <var-tabs v-model:active="active" color="rgba(255, 255, 255, 0.35)" active-color="#1e131d" inactive-color="#36292f" class="hu_tab">
            <var-tab v-for="(item,index) in cate_list" @click="go_cates(item)">{{item.name}}</var-tab>
        </var-tabs>
        <div class="hu_index">
            <Article :cates_id="cates_id" ref="Son_subassembly"/>
        </div>
    </div>
</template>

3.子组件代码实例:pinia获取父组件的值,defineExpose()暴露出子组件属性。

<script setup>
import { ref, watch } from 'vue';
import { post_articles_list,get_article_details } from "@/api/api.js";
const Art_list=ref([]);

import { useCounterStore } from "@/stores/counter.js";
const store = useCounterStore();

//子组件相关方法
let query={
    classifyID: '',
    page: 1,
    pagesize: 5 
}
const Articles_list=()=>{
	query.classifyID=store.Central_data
    post_articles_list(query).then((res) => {
        Art_list.value=res.data.data;
    }).catch((err) => {
        console.log(err)
    });
}

//通信部分方法
//传入props数据
const props = defineProps({
    cates_id: String
})
if (props.cates_id==undefined) {
    Articles_list();
}

//子组件实例暴露出属性:defineExpose
defineExpose({
    Articles_list
})
</script>

<template>
    <div class="hu_article">
        <div class="hu_son_box" v-for="(item,index) in Art_list" :key="index" @click="go_router(item.Id)">
            <div>{{ item.title }}</div>
            <div>{{ item.pub_date }}</div>
        </div>
    </div>
</template>

本文原创,原创不易,如需转载,请联系作者授权。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1093655.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【算法|动态规划No.19】leetcode413. 等差数列划分

个人主页&#xff1a;兜里有颗棉花糖 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 兜里有颗棉花糖 原创 收录于专栏【手撕算法系列专栏】【LeetCode】 &#x1f354;本专栏旨在提高自己算法能力的同时&#xff0c;记录一下自己的学习过程&#xff0c;希望…

JAVA反序列化漏洞

JAVA反序列化漏洞 原文资料&#xff1a;xiu–》xiu博客 文章目录 JAVA反序列化漏洞idea类继承反序列化漏洞person类Test类 什么是反序列化漏洞 idea 类继承 public class Person {public int age;public String name;public void talk(){System.out.println("Person 说话…

RK3588 USB WIFI调试

一.安卓wifi框架 要使用一个wifi功能需要涉及的部分有内核部分wifi驱动&#xff0c;应用部分wpa_supplicant服务。其中wifi驱动又包含很多部分&#xff0c;分为通讯接口的驱动SDIO、USB、PCIE等&#xff0c;还有上下电部分的驱动&#xff0c;wifi模组提供部分的驱动。应用部分不…

random生成随机数的灵活运用

random返回的 [0,1) 之间的一个随即小数 思考&#xff1a;请写出获取 a-b 之间的一个随机整数&#xff0c;a,b均为整数&#xff0c;比如 a2 , b7 即返回一个数 x > [2,7]Math.random()*(b-a) 返回的就是 [0,b-a](int)(aMath.random()*(b-a1)) 》 (int)(2Math.random()*6) Ma…

常用傅里叶变换表

傅里叶展开 傅里叶变换 傅里叶逆变换 时域信号 弧频域信号 线性变换 时域平移 频域平移 伸缩变换 微分性质 逆变换的微分性质 卷积定理 原函数变换结果 单位阶跃函数&#xff1a; 符号函数&#xff1a; 矩形函数&#xff1a; 辛格函数&#xff1a;

系统架构师备考倒计时22天(每日知识点)

测试阶段划分 单元测试&#xff1a;依据详细设计&#xff0c;模块测试&#xff0c;模块功能、性能、接口等集成测试&#xff1a;依据概要设计&#xff0c;模块间的接口系统测试&#xff1a;依据需求文档&#xff0c;在真实环境下&#xff0c;验证完整的软件配置项能否和系统正…

了解变分自动编码器 (VAE)

一、介绍 在过去的几年中&#xff0c;由于&#xff08;并暗示&#xff09;该领域取得了一些惊人的进步&#xff0c;基于深度学习的生成模型引起了越来越多的兴趣。依靠大量的数据、精心设计的网络架构和智能训练技术&#xff0c;深度生成模型表现出了令人难以置信的能力&#x…

Active Session History (ASH) 读书笔记

本文为博文Active Session History (ASH)的读书笔记。 AWR&#xff0c;ADDM&#xff0c;SQL Trace是对过去事件的分析&#xff0c;[G]V$视图包含大量实时信息&#xff0c;但使用界面不友好&#xff0c;对初学者较难。因此Oracle 10g推出了ASH&#xff0c;属于Oracle Diagnosti…

Linux网络编程系列之UDP广播

一、什么是UDP广播 UDP广播是一种网络通信的方式&#xff0c;在广域网或局域网中&#xff0c;UDP广播可以向多个目标主机发送数据包&#xff0c;使得网络中的所有设备都能接收到广播消息。一定是采用UDP协议。 二、特性 1、面向无连接&#xff1a;UDP广播不需要建立连接&#…

PLC易学但是后期如何发展?

今日话题 PLC易学但是后期如何发展&#xff1f; PLC学习简便&#xff0c;但重要性不容小觑。除基础外&#xff0c;以下为几个技术方向&#xff1a; 大规模系统&#xff1a;包括冗余PLC、网络架构和服务器。掌握虚拟化、网络设计和模块化。 特色系统&#xff1a;如电力行业…

FastAdmin前台分片传输上传文件getshell

漏洞概述 FastAdmin框架存在有条件RCE漏洞&#xff0c;由于FastAdmin的前台文件上传功能中提供了分片传输功能, 但在合并分片文件时因对文件路径的拼接处理不当导致可上传任意文件。 漏洞复现 漏洞需要一个低权限的账号 所以我们需要在前台注册一个普通用户 注册成功后进行…

1. 树的建立与基本操作

程序的输入是一个表示树结构的广义表。假设树的根为 root &#xff0c;其子树森林 F &#xff1d; &#xff08; T1 &#xff0c; T2 &#xff0c; … &#xff0c; Tn &#xff09;&#xff0c;设与该树对应的广义表为 L &#xff0c;则 L &#xff1d;&#xff08;原子&#…

TLS/SSL 详解

目录 基础理论入门HTTPS对称加密非对称加密证书TLS握手过程握手总结 TLS 定义(记录层/握手层)HTTPS HTTP over TLS加密记录层分片 (Fragmentation)记录压缩和解压缩 (Record compression and decompression)空或标准流加密 (Null or standard stream cipher)CBC 块加密 (分组加…

NV21图片格式深入解析与代码实战-RGB转NV21与画框

1.NV21格式图片解析 NV21图像格式属于 YUV颜色空间中的YUV420SP格式 每四个Y分量共用一组U分量和V分量&#xff0c;Y连续排序&#xff0c;U与V交叉排序 重点总结 uv交错模式4Y共用一组uv(2个)大小&#xff1a;UV Y 的一半 排列方式如下 Y Y   Y Y   Y Y   Y Y Y Y   Y Y…

001数据安全传输-多端协议传输平台:Openssl安装和配置 - EVP代码测试

001数据安全传输-多端协议传输平台&#xff1a;Openssl安装和配置 - EVP代码测试 文章目录 001数据安全传输-多端协议传输平台&#xff1a;Openssl安装和配置 - EVP代码测试1. 安装1.1 windows下安装openssl1.2 Linux下安装OpenSSL 2. VS中使用openssl3. 测试 1. 安装 1.1 win…

ionic+vue+capacitor系列笔记--常用操作代码合集(图片引用,axios跨域配置,去除按钮波纹)

1.单个图片引用 html <img :src"userImgSrc" />ts <script lang"ts"> import { defineComponent } from "vue"; export default defineComponent({name: "Tab1Page",components: {},setup(props, context) {let url &…

FFmpeg截图命令优化

由于项目要求&#xff0c;需要对摄像机的rtsp流进行截图。一开始我使用了命令&#xff1a; ./ffmpeg -ss 0 -i XXX -f image2 -vframes 1 -s 370*210 -y output.jpg 上述命令抓取rtsp流第0秒&#xff08;当前&#xff09;的图像&#xff0c;将其保存为370*210分辨率的jpg图片…

清理日志后出现 no boot device available,不能启动处理

3号LNS清理日志后出现 no boot device available&#xff0c;不能启动处理 然后 不知道为什么&#xff0c;清理系统日志后&#xff0c;就这样了&#xff0c; 然后按下F11&#xff0c;选择硬盘启动就好了&#xff0c;不要选择USB那个&#xff01; ...... 这样是能启动了&#xf…

延时盲注(CVE-2022-0948)

详解&#xff1a; 延时盲注&#xff0c;也称为时间盲注或延迟注入&#xff0c;是一种利用执行时间差判断是否执行成功的盲注手法。攻击者提交一个对执行时间敏感的SQL语句&#xff0c;通过执行时间的长短来判断注入是否成功。例如&#xff0c;如果注入成功&#xff0c;执行时间…

互联网Java工程师面试题·Java 并发编程篇·第七弹

目录 16、CAS 的问题 17、什么是 Future&#xff1f; 18、什么是 AQS 19、AQS 支持两种同步方式&#xff1a; 20、ReadWriteLock 是什么 21、FutureTask 是什么 22、synchronized 和 ReentrantLock 的区别 23、什么是乐观锁和悲观锁 24、线程 B 怎么知道线程 A 修改了…