10 Must‑Know Vue3 Tricks to Supercharge Your Frontend Projects

Discover ten practical Vue3 techniques—including shallowRef, shallowReactive, toRef/toRefs, watchPostEffect, v‑for keys, custom hooks, v‑model modifiers, keep‑alive, and Web Workers—that boost performance, simplify data handling, and enhance component development for modern frontend projects.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
10 Must‑Know Vue3 Tricks to Supercharge Your Frontend Projects
Front‑end developers, we all have faced data update glitches, tangled component communication, and slow page loads in Vue3 projects. As an experienced veteran, I’m sharing ten ultra‑practical Vue3 techniques to turn these pain points into powerful tools.

shallowRef and shallowReactive — lightweight reactive guards

When handling large data structures, deep reactivity can cause performance issues. shallowRef focuses on primitive values and reacts only on direct assignment, while shallowReactive watches only top‑level properties.

Example: using shallowReactive on a table of ten thousand employees improved rendering speed by about 30%.

import { shallowRef, shallowReactive } from 'vue';

const simpleCount = shallowRef(0);
simpleCount.value = 1;

const user = {
  name: 'Alice',
  address: {
    city: 'Beijing',
    street: 'Xinhua Road'
  }
};
const shallowUser = shallowReactive(user);
shallowUser.name = 'Bob';
// shallowUser.address.city = 'Shanghai'; // not reactive

toRef and toRefs — smart data unpackers

toRef

extracts a single property while preserving reactivity; toRefs extracts multiple properties as a collection of refs.

import { reactive, toRef, toRefs } from 'vue';

const product = reactive({
  title: 'Vue3 Practical Guide',
  price: 99,
  stock: 100
});
const productTitle = toRef(product, 'title');
productTitle.value = 'Vue3 Advanced Secrets';

const { price, stock } = toRefs(product);
price.value = 89;
stock.value = 80;

watchPostEffect — the “late‑arriving” watcher

watchPostEffect

runs its callback after the component has finished updating and the DOM is rendered, avoiding timing bugs.

import { ref, watchPostEffect } from 'vue';

const count = ref(0);
watchPostEffect(() => {
  console.log(`Page updated, count is: ${count.value}`);
});
count.value++;

v‑for key — list rendering identifier

Providing a unique key for each item lets Vue efficiently diff and update lists, preventing rendering glitches.

<template>
  <ul>
    <!-- Unique key for each list item -->
    <li v-for="item in userList" :key="item.id">
      {{ item.name }} - {{ item.age }}
    </li>
  </ul>
</template>

<script>
import { ref } from 'vue';
export default {
  setup() {
    const userList = ref([
      { id: 1, name: 'Tom', age: 25 },
      { id: 2, name: 'Jerry', age: 23 }
    ]);
    return { userList };
  }
};
</script>

Custom Hooks — reusable logic factories

Encapsulate repetitive logic such as form handling into composable functions.

import { ref, watch } from 'vue';

function useFormInput() {
  const inputValue = ref('');
  const errorMessage = ref('');
  const validate = () => {
    if (inputValue.value.trim() === '') {
      errorMessage.value = 'Input cannot be empty';
      return false;
    }
    errorMessage.value = '';
    return true;
  };
  watch(inputValue, () => {
    validate();
  });
  return { inputValue, errorMessage, validate };
}
export default useFormInput;

Using the hook in a component simplifies form validation and state management.

<template>
  <div>
    <input v-model="form.inputValue" placeholder="Enter something">
    <p v-if="form.errorMessage">{{ form.errorMessage }}</p>
    <button @click="submitForm" :disabled="!form.validate()">Submit</button>
  </div>
</template>

<script>
import useFormInput from './useFormInput';
export default {
  setup() {
    const form = useFormInput();
    const submitForm = () => {
      if (form.validate()) {
        console.log('Form validated, submitting data');
      }
    };
    return { form, submitForm };
  }
};
</script>

v‑cloak — hide unrendered template expressions

Applying v‑cloak prevents the raw {{ }} bindings from flashing before Vue mounts.

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>v-cloak example</title>
  <style>
    [v-cloak] { display: none; }
  </style>
</head>
<body>
  <div id="app" v-cloak>{{ message }}</div>
  <script type="module">
    import { createApp } from 'vue';
    const app = createApp({
      data() {
        return { message: 'Welcome to Vue3!' };
      }
    });
    app.mount('#app');
  </script>
</body>
</html>

v‑slot — flexible component content distribution

Named slots and scoped slots let parent components inject and retrieve content dynamically.

<template>
  <MyComponent>
    <template v-slot:header>
      <h2>Component Header</h2>
    </template>
    <template v-slot:default>
      <p>Main component body</p>
    </template>
  </MyComponent>
</template>

<script>
import MyComponent from './MyComponent.vue';
export default { components: { MyComponent } };
</script>

<!-- MyComponent.vue -->
<template>
  <div>
    <slot></slot> <!-- default slot -->
    <slot name="header"></slot>
  </div>
</template>
<script>export default {};</script>

v‑model modifiers — handy form‑input assistants

.number converts input to a number, .trim removes surrounding whitespace, and .lazy updates the model only on change events.

<template>
  <div>
    <input v-model.number="age" type="text">
    <input v-model.trim="username" type="text">
    <input v-model.lazy="message" type="text">
  </div>
</template>

<script>
import { ref } from 'vue';
export default {
  setup() {
    const age = ref(0);
    const username = ref('');
    const message = ref('');
    return { age, username, message };
  }
};
</script>

keep‑alive — component caching repository

Wrapping dynamic components with keep‑alive preserves their state between navigations, reducing re‑render costs.

<template>
  <div>
    <button @click="activeTab = 'tab1'">Tab 1</button>
    <button @click="activeTab = 'tab2'">Tab 2</button>
    <keep-alive>
      <component :is="activeTab"></component>
    </keep-alive>
  </div>
</template>

<script>
import Tab1 from './Tab1.vue';
import Tab2 from './Tab2.vue';
import { ref } from 'vue';
export default {
  components: { Tab1, Tab2 },
  setup() {
    const activeTab = ref('tab1');
    return { activeTab };
  }
};
</script>

Web Workers — background thread helpers

Offload heavy calculations to a worker script to keep the UI responsive.

// worker.js
self.onmessage = function (e) {
  console.log('Message from main thread:', e.data);
  let result = 0;
  for (let i = 1; i <= 1000000; i++) {
    result += i;
  }
  self.postMessage(`Task completed, result: ${result}`);
};

Integrating a worker in a Vue3 app enables multi‑threaded processing without blocking the main thread.

These ten Vue3 practical tricks cover data handling, performance optimization, component design, and multithreading, providing a solid toolbox for modern frontend development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendperformanceWeb WorkershooksComponent DesignVue3Reactivity
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.