惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Destructure Props in Vue (Composition API)
Dmitri Pavlutin · 2023-01-11 · via Dmitri Pavlutin Blog
Post cover

The reactivity API adds many possibilities to the composition API while keeping the code brief. However, you should be aware of some of the pitfalls of reactivity, for example, losing reactivity.

In this post, you will learn how to correctly destructure props of a Vue component so that props do not lose reactivity.

1. Destructuring props

The compiler macro defineProps() helps to access the props supplied to a component inside the setup script:


<script lang="ts" setup>

const props = defineProps()

// ...

</script>


props in the above example is a reactive object containing the props supplied to the component. If the component props changes, props reactive object changes accordingly.

The first thing you might want to do when accessing the props object is to destructure it to access the individual props. But to my surprise (when I was learning Vue composition API) the destructured props lose their reactivity!

Let's look at an example. The following component <EvenOdd :count="5"> accepts a count prop as a number, and displays a message whether count is even or odd.

The count prop is accessed after destructuring of the props object const { count } = defineProps():


<script lang="ts" setup>

import { computed } from 'vue';

const { count } = defineProps<{ count: number }>(); // Don't do this!

const even = computed(() => (count % 2 === 0 ? 'even' : 'odd'));

</script>

<template>The number is {{ even }}</template>


Open the demo

Open the demo and click a few times the increase button. You'd notice that "The number is even" message always stays the same despite the count prop increasing.

When destructuring the props object const { count } = defineProps() the reactivity is lost.

The reactivity is lost because on destructuring count becomes a variable having a primitive value (a number). But Vue's reactivity cannot work directly on primitive values: it works either using a ref or a reactive object.

Be careful when assigning a primitive value directly to a variable in Vue: that's a premise of lost reactivity.

2. Solution 1: use "props" object

The first obvious solution is to not destructure the props object, and access the props directly using a property accessor: props.count.


<script lang="ts" setup>

import { computed } from 'vue';

const props = defineProps<{ count: number }>();

const even = computed(() => (props.count % 2 === 0 ? 'even' : 'odd'));

</script>

<template>The number is {{ even }}</template>


Open the demo.

In the example above accessing props.count inside computed() maintains the reactivity when props.count changes. props object is reactive and any changes to it are tracked correctly.

The downside of this approach is you always have to use a property accessor (e.g. props.count) to access a prop inside of the setup script.

Anyways, I recommend using props object directly in most cases.

3. Solution 2: use toRefs() helper

If you continue reading I bet you're big a fan of destructuring and cannot live without it.

Ok, then you can keep the reactivity of the destructured props by deliberately transforming each property of the props object into a ref. Vue provides a special helper toRefs(reactiveObject) that does this exactly.

Here's how it works:


<script lang="ts" setup>

import { toRefs, computed } from 'vue';

const props = defineProps<{ count: number }>();

const { count } = toRefs(props);

const even = computed(() => (count.value % 2 === 0 ? 'even' : 'odd'));

</script>

<template>The number is {{ even }}</template>


Open the demo.

toRefs(props) returns an object where each property is a ref to the corresponding prop.

Now the destructuring const { count } = toRefs(props) is safe because count is a ref to the "count" prop. Now every time the "count" prop changes, the ref count reacts to the prop change.

Having count as a ref, inside the computed() you have to access the prop value using count.value (because count.value is how you access the value of a ref).

I find this approach convenient to pass the prop ref as an argument to a composable: e.g. useMyComposable(count) and not lose reactivity.

Otherwise, I'd stick to the previous approach by using props object directly to access the props.

4. Conclusion

Be aware that by applying the destructuring const { propA, propB } = defineProps() you lose the reactivity of props.

There are mainly 2 approaches to solving the lost reactivity.

The first one is to simply not destructure props, but rather access the props directly using a property accessor: props.propA, props.propsB.

The second approach involves deliberately using the props as an object of refs: const { propA, propB } = toRefs(props). This keeps the reactivity after destructuring. Then you can access properties as standalone refs, e.g. propsA.value, propB.value, etc.

What tricky cases of reactivity loss in Vue do you know?

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸