search
HomeWeb Front-endVue.jsNote that Vue's reactive syntactic sugar has been deprecated!

This article brings you the latest situation about Vue. It mainly talks about the responsive syntax sugar in Vue. Friends who are interested can take a look at it together. I hope it will be helpful to everyone.

Note that Vue's reactive syntactic sugar has been deprecated!

Introduction

Since the introduction of the concept of composite APIs, a major unsolved problem has been ref# Which one should I use between ## and reactive? reactive has the problem of losing responsiveness due to deconstruction, while ref needs to be used everywhere .value feels cumbersome and can easily be missed without the help of the type system. Drop .value.

For example, the following counter:

<template>
  <button>{{ count }}</button>
</template>
Use

ref to define the count variable and increment method:

let count = ref(0)

function increment() {
  count.value++
}
Using responsive syntax sugar, we can write code like this:

let count = $ref(0)

function increment() {
  count++
}
    Vue’s responsive syntax sugar is a compile-time conversion step,
  1. $ref() The method is a compile-time macro command. It is not a real method that will be called at runtime, but is used as a marker for the Vue compiler to indicate the final count The variable needs to be a reactive variable.
  2. Reactive variables can be accessed and reassigned like ordinary variables, but these operations will become
  3. ref with .value after compilation. So the code in the above example will also be compiled into the syntax defined using ref.
  4. Each reactive API that returns
  5. ref has a corresponding macro function prefixed with $. Including the following APIs:
    ref -> $ref
  • computed -> $computed
  • shallowRef -> $shallowRef
  • customRef -> $customRef
  • toRef -> $toRef
##You can use the
    $()
  1. macro to convert an existing ref Convert to reactive variables.
    const a = ref(0)
    let count = $(a)
    count++
    console.log(a.value) // 1
You can use the
    $$()
  1. macro to keep any reference to a reactive variable as a reference to the corresponding ref.
    let count = $ref(0)
    console.log(isRef($$(count))) // true
$$()

also works with destructured props since they are also reactive variables. The compiler will efficiently do the conversion through toRef: <pre class="brush:php;toolbar:false">const { count } = defineProps() passAsRef($$(count))</pre>Configuration

Responsive syntactic sugar is a unique feature of

Combined API

, and Must be used via the build step.

Required, requires
    @vitejs/plugin-vue@>=2.0.0
  1. , will be applied to SFC and js(x)/ts(x) files.
    // vite.config.js
    export default {
      plugins: [
        vue({
          reactivityTransform: true
        })
      ]
    }
Note
    reactivityTransform
  • is now a top-level option of a plug-in, and is no longer located in script.refSugar, because it is not only Only effective for SFC.
  • If it is
vue-cli

build, vue-loader@>=17.0.0 is required. It is currently only effective for SFC. <pre class="brush:php;toolbar:false">// vue.config.js module.exports = {   chainWebpack: (config) =&gt; {     config.module       .rule('vue')       .use('vue-loader')       .tap((options) =&gt; {         return {           ...options,           reactivityTransform: true         }       })   } }</pre> If

webpack

vue-loader is built, vue-loader@>=17.0.0 is required, currently only for SFC. effect. <pre class="brush:php;toolbar:false">// webpack.config.js module.exports = {   module: {     rules: [       {         test: /\.vue$/,         loader: 'vue-loader',         options: {           reactivityTransform: true         }       }     ]   } }</pre>

Optional, add the following code to the
    tsconfig.json
  1. file, otherwise an error will be reported TS2304: Cannot find name '$ref'., although it does not It affects the use, but it will affect the development experience:
    "compilerOptions":{ "types": ["vue/ref-macros"] }
Optional, add the following code to the
    eslintrc.cjs
  1. file, otherwise it will prompt ESLint: '$ ref' is not defined.(no-undef)
    module.exports = { ...globals: {
        $ref: "readonly",
        $computed: "readonly",
        $shallowRef: "readonly",
        $customRef: "readonly",
        $toRef: "readonly",
      }
    };
When responsive syntactic sugar is enabled, these macro functions are globally available and do not need to be imported manually. You can also explicitly introduce
    vue/macros
  1. in the vue file, so that there is no need to configure tsconfig.json and eslintrc in the second and third steps.
    import { $ref } from 'vue/macros'
    
    let count = $ref(0)
  2. Deprecated experimental feature

    Responsive syntax sugar was once an experimental feature and has been deprecated, please read
  • Deprecated reason

    .

  • It will be removed from Vue core in a future minor version update. If you want to continue using it, please use the
  • Vue Macros

    plug-in.

  • Reason for abandonment

You Yuxi personally gave the reason for abandonment 2 weeks ago (10:05 am GMT 8, February 21, 2023) , the translation is as follows:

As many of you already know, we have officially abandoned this RFC by consensus of the team.

reason

The original goal of Reactivity Transform was to improve the developer experience by providing a cleaner syntax when dealing with reactive state. We're releasing it as an experimental product to gather feedback from real-world usage. Despite these proposed benefits, we discovered the following issues:

  • Losing .value makes it harder to tell what is being tracked and which line triggered the reactive effect . This problem is less obvious in small SFCs, but in large code bases the mental overhead becomes more obvious, especially if the syntax is also used outside of SFC .

  • Due to (1), some users choose to only use Reactivity Transform inside SFC, which creates inconsistencies and context switching costs between different mental models. So the dilemma is that using it only inside SFC will lead to inconsistencies, but using it outside SFC will hurt maintainability.

  • Since there will still be external functions that expect to use raw references, conversion between reactive variables and raw references is inevitable. This ended up adding more learning content and additional mental load, which we noticed was more confusing for beginners than the normal Composition API.

The most important thing is the potential risk of fragmentation. Although this is an explicit opt-in, some users have expressed strong opposition to the proposal due to concerns that they will have to work with different code bases where some have opted in to use it and others No. This is a legitimate concern because Reactivity Transform requires a different mental model and distorts JavaScript semantics (variable assignments can trigger reactive effects).

All things considered, we feel that using this as a stable feature will cause more problems than benefits and is therefore not a good trade-off.

Migration Plan

Message

  • Although Reactivity Transform will be removed from the official package, I think it is a good attempt.
  • Well written. I like detailed RFCs and objective evaluation based on user feedback. The final conclusion makes sense. Don’t let perfect be the enemy of good.
  • Although I enjoy the convenience of this feature, I did find this potential fragmentation issue in actual use. There may be some reluctance to remove this feature in a future release, but engineers should take it seriously. ?
  • Do you remove all functions or just the ref.value part that does the conversion? What about reactive props Deconstruction, is it here to stay?
  • I have been using it for a medium sized e-commerce website without any issues. I understand the rationale behind removing it, but in practice I've found it to be a really big improvement. So my question is: what now?
  • Is it recommended that people who hate .value now avoid ref() if possible and use reactive() like before?
  • .value is the necessary complexity. Just like any other reactive library xxx.set().
  • It should be easy to create a package that transforms all the Reactivity Transform code, right? I also like to do things the recommended way.
  • ...

Recommended study: "vue.js video tutorial"

The above is the detailed content of Note that Vue's reactive syntactic sugar has been deprecated!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft