Home > Web Front-end > Vue.js > Note that Vue's reactive syntactic sugar has been deprecated!

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

藏色散人
Release: 2023-03-06 16:00:19
forward
2860 people have browsed it

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 @click="increment">{{ count }}</button>
</template>
Copy after login
Use

ref to define the count variable and increment method:

let count = ref(0)

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

let count = $ref(0)

function increment() {
  count++
}
Copy after login
    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
    Copy after login
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
    Copy after login
$$()

also works with destructured props since they are also reactive variables. The compiler will efficiently do the conversion through toRef: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const { count } = defineProps&lt;{ count: number }&gt;() passAsRef($$(count))</pre><div class="contentsignin">Copy after login</div></div>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
        })
      ]
    }
    Copy after login
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. <div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div> If

webpack

vue-loader is built, vue-loader@>=17.0.0 is required, currently only for SFC. effect. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// webpack.config.js module.exports = {   module: {     rules: [       {         test: /\.vue$/,         loader: 'vue-loader',         options: {           reactivityTransform: true         }       }     ]   } }</pre><div class="contentsignin">Copy after login</div></div>

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"] }
    Copy after login
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",
      }
    };
    Copy after login
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)
    Copy after login
  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!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template