Vue3中的常用组件通信大总结 包括最Vue3.4defineModel()实现组件双向绑定

本文主要是介绍Vue3中的常用组件通信大总结 包括最Vue3.4defineModel()实现组件双向绑定,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

Vue中官网是这么介绍组件的:组件允许我们将UI划分为独立的、可重用的部分,并且对每个部分进行单独的思考

如果一个文件包含四五个组件,那么他们之间的数据通信如何解决呢,所以组件中数据通信是Vue中非常重要的知识

父传子(子组件使用父组件的 state&& function)

props
//父组件
<template>
<div>
这是父组件
</div>
<child :state=state :ParentFn=ParentFn></child>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import child from "./components/index.vue"
const state = ref<string>('这是父组件的state')
const ParentFn =() => {
console.log('这是父组件的方法')
}
</script>
//子组件
<template>
<div>这是子组件</div>
<div>这是父组件传过来的值{{ props.state}}</div>
<button @click="props.ParentFn">触发父组件方法</button>
</template>
<script lang="ts" setup>
const props = defineProps({state: String,ParentFn:Function,})
</script>
attrs:包含父作用域里除 class 和 style 除外的非 props 属性集合
//父组件
<template>
<child :msg1="msg1" :msg2="msg2" title="good"></child>
</template>
<script setup>
import child from "./components/index.vue"
import { ref, reactive } from "vue"
const msg1 = ref(1)
const msg2 = ref(2)
</script>
//子组件
<template>
<div>{{attrs}}</div>
</template>
<script lang="ts" setup>
import {useAttrs} from "vue"
defineProps({
msg1: Number
})
const attrs = useAttrs()
console.log(attrs) //{ "msg2": 2, "title": "good" }
</script>
//子组件第二种使用方式
//将父组件传递的所有非 prop 属性绑定到子组件的元素上
<template>
<div v-bind="$attrs"></div>
</template>

子传父(父组件使用子组件的state &&function)

emit这个方法我用的比较少 代码比较繁琐且难用
//父组件
<template>
<child @myClick="onMyClick"/>
</template>
<script setup lang="ts">
import child from "./components/index.vue"
const onMyClick = (msg:any) => {
console.log(msg) // 这是父组件收到的信息
}
</script>
//子组件
<template>
<div>这是子组件</div>
<button @click="handleClick">按钮</button>
</template>
<script lang="ts" setup>
const emit = defineEmits(["myClick"])
const handleClick = ()=>{
emit("myClick", "这是发送给父组件的信息")
}
</script>
defineExpose + ref

ref绑定在子组件上可以在父组件中来访问子组件的实例

在子组件使用defineExpose暴露方法或变量

//父组件
<template><div> 这是父组件</div><div> 这是子组件的数据{{childRef?.state }}</div><button @click="childRef!.fnFromChild">触发子组件</button><child ref="childRef"></child></template>
<script setup lang="ts">import { ref } from 'vue';import child from "./components/index.vue"const childRef = ref<null | {state:string,fnFromChild:Function}>(null)</script>//这是子组件
<template><div>这是子组件</div></template>
<script lang="ts" setup>
import { ref } from 'vue';
const state = ref<string>("hello")
const fnFromChild = () => {
console.log('这是子组件的方法')
}
defineExpose(
{
state,
fnFromChild
}
)
</script>

v-model: 在子组件直接修改父组件数据

//这是父组件<template>
<div> 这是父组件{{ params }}</div>
<child v-model="params"></child>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import child from "./components/index.vue"
const params = ref<string>('1')
</script>
//这是子组件
<template>
<div>这是子组件{{ modelValue }}</div>
</template>
<script lang="ts" setup>
defineProps({
modelValue: String
})
//实现了父传子</script>
// 实现子组件修改父组件数据
<template>
<div>这是子组件{{ modelValue }}</div>
<button @click="updateValue">子组件的方法 改变父组件数据</button>
</template><script lang="ts" setup>
defineProps({
modelValue: String
})
const emit = defineEmits(["update:modelValue"])
const updateValue = () => {
emit("update:modelValue","我是父组件的值 我被子组件改变的")
}
</script>

v-model在组件上使用双向绑定

从 Vue 3.4 开始,推荐的实现方式是使用 defineModel()其实就是上述例子的语法糖

defineModel() 返回的值是一个 ref, 它的 .value 和父组件的 v-model 的值同步

⚠️ 注意
如果为 defineModel prop 设置了一个 default 值且父组件没有为该 prop 提供任何值,会导致父组件与子组件之间不同步

//父组件
<template>
<div> 这是父组件{{ count}}</div>
<child v-model="count"></child>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import child from "./components/index.vue"
const count= ref<number>(1)
</script>//子组件
<template>
<div>这是子组件{{ model}}</div>
<button @click="update">子组件的方法 改变父组件数据</button>
</template>
<script lang="ts" setup>
const model = defineModel({default : 1})
function update() {
model.value++
}
</script>

组件上的 v-model 也可以接受一个参数

//父组件
<child v-model:title="bookTitle" />
//子组件
<script setup>
const title = defineModel('title')
</script><template><input type="text" v-model="title" />
</template>

多个v-model绑定

//父组件
<child v-model:first-name="first" v-model:last-name="last" />
//子组件
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script><template><input type="text" v-model="firstName" /><input type="text" v-model="lastName" />
</template>

祖孙通信 provide && inject

用于提供可以被后代组件注入的值

这个组件库用的多些,因为组件库不知道你会在哪使用它提供的值

//先代组件
<script setup>
import { ref, provide } from 'vue'
import { countSymbol } from './injectionSymbols'
// 提供静态值
provide('path', 'good')
// 提供响应式的值
const count = ref(0)
provide('count', count)
// 提供时将 Symbol 作为 key
provide(countSymbol, count)
</script>
//后代组件
<script setup>
import { inject } from 'vue'
import { countSymbol } from './injectionSymbols'
// 注入不含默认值的静态值
const path = inject('path')
// 注入响应式的值
const count = inject('count')
// 通过 Symbol 类型的 key 注入
const count2 = inject(countSymbol)
// 注入一个值,若为空则使用提供的默认值
const bar = inject('path', '/default-path')
</script>

全局通信 Pinia

接下来贴一波日常使用的代码
创建文件夹stroe
创建文件index.ts

//这样引入方便pinia使用插件比如
// 比如持久化 pinia.use(piniaPluginPersistedstate)
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
//在main.ts中
import pinia from '@/stores'
app.use(pinia)

创建文件user.ts

import { defineStore } from 'pinia'
import { UserState } from '@/stores/interface'
export const useUserStore = defineStore('Oner-user', {
state: (): UserState => ({
token: '',
userInfo: { name: 'Oner' },
userVerify: '',
currentPage: 0,
}),
getters: {},
actions: {
// Set Token
setToken(token: string) {
this.token = token
},
// Set setUserInfo
setUserInfo(userInfo: UserState['userInfo']) {
this.userInfo = userInfo
},
setUserVerify(verify: string) {
this.userVerify = verify
},
setCurrentPage(value: number) {
this.currentPage = value
},
},
})

在任意组件中使用

const userStore = useUserStore()
console.log(userStore.token) // ''
console.log(userStore.setToken("zhaimoudetoken"))
console.log(userStore.token) // zhaimoudetoken

文章到这里就结束了,希望对你有所帮助。

这篇关于Vue3中的常用组件通信大总结 包括最Vue3.4defineModel()实现组件双向绑定的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/922129

相关文章

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL常用字符串函数示例和场景介绍

《MySQL常用字符串函数示例和场景介绍》MySQL提供了丰富的字符串函数帮助我们高效地对字符串进行处理、转换和分析,本文我将全面且深入地介绍MySQL常用的字符串函数,并结合具体示例和场景,帮你熟练... 目录一、字符串函数概述1.1 字符串函数的作用1.2 字符串函数分类二、字符串长度与统计函数2.1

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali