在我的工作场所,我的任务是为内部本地开发工作创建一个模拟聊天商店,在这样做的同时,我做了一些关于 Vue 的笔记(我有一些经验,但没有hooks),所以这只是我的黑曜石笔记,希望对你有用:)
目录
- 参考和反应参考
- 观看和反应
- Pinia 商店集成
- 实际例子
- 最佳实践
- 常见问题
参考文献和反应参考文献
什么是参考?
ref 是 Vue 使原始值具有响应性的方式。它将值包装在带有 .value 属性的响应式对象中。
import { ref } from 'vue' // Inside Pinia Store export const useMyStore = defineStore('my-store', () => { // Creates a reactive reference const count = ref<number>(0) // To access or modify: function increment() { count.value++ // Need .value for refs } return { count, // When exposed, components can use it without .value increment } }) </number>
商店中的参考文献类型
// Simple ref const isLoading = ref<boolean>(false) // Array ref const messages = ref<message>([]) // Complex object ref const currentUser = ref<user null>(null) // Ref with undefined const selectedId = ref<string undefined>(undefined) </string></user></message></boolean>
观察和反应
手表的基本使用
import { watch, ref } from 'vue' export const useMyStore = defineStore('my-store', () => { const messages = ref<message>([]) // Simple watch watch(messages, (newMessages, oldMessages) => { console.log('Messages changed:', newMessages) }) }) </message>
观看选项
// Immediate execution watch(messages, (newMessages) => { // This runs immediately and on changes }, { immediate: true }) // Deep watching watch(messages, (newMessages) => { // Detects deep object changes }, { deep: true }) // Multiple sources watch( [messages, selectedId], ([newMessages, newId], [oldMessages, oldId]) => { // Triggers when either changes } )
Pinia 商店集成
带有引用的存储结构
export const useMyStore = defineStore('my-store', () => { // State const items = ref<item>([]) const isLoading = ref(false) const error = ref<error null>(null) // Computed const itemCount = computed(() => items.value.length) // Actions const fetchItems = async () => { isLoading.value = true try { items.value = await api.getItems() } catch (e) { error.value = e as Error } finally { isLoading.value = false } } return { items, isLoading, error, itemCount, fetchItems } }) </error></item>
组合商店
export const useMainStore = defineStore('main-store', () => { // Using another store const otherStore = useOtherStore() // Watching other store's state watch( () => otherStore.someState, (newValue) => { // React to other store's changes } ) })
实际例子
自动刷新实现
export const useChatStore = defineStore('chat-store', () => { const messages = ref<message>([]) const refreshInterval = ref<number null>(null) const isRefreshing = ref(false) // Watch for auto-refresh state watch(isRefreshing, (shouldRefresh) => { if (shouldRefresh) { startAutoRefresh() } else { stopAutoRefresh() } }) const startAutoRefresh = () => { refreshInterval.value = window.setInterval(() => { fetchNewMessages() }, 5000) } const stopAutoRefresh = () => { if (refreshInterval.value) { clearInterval(refreshInterval.value) refreshInterval.value = null } } return { messages, isRefreshing, startAutoRefresh, stopAutoRefresh } }) </number></message>
加载状态管理
export const useDataStore = defineStore('data-store', () => { const data = ref<data>([]) const isLoading = ref(false) const error = ref<error null>(null) // Watch loading state for side effects watch(isLoading, (loading) => { if (loading) { // Show loading indicator } else { // Hide loading indicator } }) // Watch for errors watch(error, (newError) => { if (newError) { // Handle error (show notification, etc.) } }) }) </error></data>
最佳实践
1. 参考初始化
// ❌ Bad const data = ref() // Type is 'any' // ✅ Good const data = ref<string>([]) // Explicitly typed </string>
2. 观察清理
// ❌ Bad - No cleanup watch(source, () => { const timer = setInterval(() => {}, 1000) }) // ✅ Good - With cleanup watch(source, () => { const timer = setInterval(() => {}, 1000) return () => clearInterval(timer) // Cleanup function })
3. 计算与观看
// ❌ Bad - Using watch for derived state watch(items, (newItems) => { itemCount.value = newItems.length }) // ✅ Good - Using computed for derived state const itemCount = computed(() => items.value.length)
4. 店铺组织
// ✅ Good store organization export const useStore = defineStore('store', () => { // State refs const data = ref<data>([]) const isLoading = ref(false) // Computed properties const isEmpty = computed(() => data.value.length === 0) // Watchers watch(data, () => { // Handle data changes }) // Actions const fetchData = async () => { // Implementation } // Return public interface return { data, isLoading, isEmpty, fetchData } }) </data>
常见问题
- 忘记.value
// ❌ Bad const count = ref(0) count++ // Won't work // ✅ Good count.value++
- 观看时间
// ❌ Bad - Might miss initial state watch(source, () => {}) // ✅ Good - Catches initial state watch(source, () => {}, { immediate: true })
- 内存泄漏
// ❌ Bad - No cleanup const store = useStore() setInterval(() => { store.refresh() }, 1000) // ✅ Good - With cleanup const intervalId = setInterval(() => { store.refresh() }, 1000) onBeforeUnmount(() => clearInterval(intervalId))
记住:在 Pinia 商店
与裁判和手表合作时,请始终考虑清理、类型安全和适当的组织
以上是了解 Vue 与 Pinia Store 的反应性的详细内容。更多信息请关注PHP中文网其他相关文章!

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

Node.js擅长于高效I/O,这在很大程度上要归功于流。 流媒体汇总处理数据,避免内存过载 - 大型文件,网络任务和实时应用程序的理想。将流与打字稿的类型安全结合起来创建POWE

Python和JavaScript在性能和效率方面的差异主要体现在:1)Python作为解释型语言,运行速度较慢,但开发效率高,适合快速原型开发;2)JavaScript在浏览器中受限于单线程,但在Node.js中可利用多线程和异步I/O提升性能,两者在实际项目中各有优势。

JavaScript起源于1995年,由布兰登·艾克创造,实现语言为C语言。1.C语言为JavaScript提供了高性能和系统级编程能力。2.JavaScript的内存管理和性能优化依赖于C语言。3.C语言的跨平台特性帮助JavaScript在不同操作系统上高效运行。

JavaScript在浏览器和Node.js环境中运行,依赖JavaScript引擎解析和执行代码。1)解析阶段生成抽象语法树(AST);2)编译阶段将AST转换为字节码或机器码;3)执行阶段执行编译后的代码。

Python和JavaScript的未来趋势包括:1.Python将巩固在科学计算和AI领域的地位,2.JavaScript将推动Web技术发展,3.跨平台开发将成为热门,4.性能优化将是重点。两者都将继续在各自领域扩展应用场景,并在性能上有更多突破。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Atom编辑器mac版下载
最流行的的开源编辑器