Analysis of the Assembled API of Vue 3.0 (I)

  • 2021-08-09 07:06:04
  • OfStack

(1) Responsive data

1. Simple examples

Starting with the simplest data binding, in Vue 2.0, we bind 1 piece of data to the specified location of the template as follows:

Returns 1 data object for binding in the data constructor of the component creation parameter, including now Field, it will be rendered to the .app > p Inside.


<template>
  <div class="app">
    <h1>Hello world!</h1>
    <p>Now is: {{now.toString()}}</p>
  </div>
</template>

<script>
// Vue 2.0
export default {
  data() {
    return {
      now: new Date(),
    };
  },
};
</script>

If implemented with API, the assembly of Vue3, this is the case:


// Vue 3.0
export default {
  setup() {
    return {
      now: new Date(),
    };
  },
};

Step 2 Update data

Strange, it doesn't seem to make any difference, just put data Changed to setup Is it?

No, if we make a small change to this DEMO now and let it refresh once every second, it would be like this with Vue2:


// Vue 2.0
export default {
  data() {
    return {
      now: new Date(),
    };
  },
  mounted() {
    setInterval(() => this.now = new Date(), 1000);
  },
};

The equivalent implementation of Vue3 is:


// Vue 3.0
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const now = ref(new Date());
    onMounted(() => {
      setInterval(() => now.value = new Date(), 1000);
    });
    return {
      now,
    };
  },
};

3. Comparative analysis

Those of us who have written too much Vue may have forgotten how strange the code for Vue2 is from the standpoint of the standard JS module:

mounted Modified in this.now Where is the data created? We are in the module default The corresponding field is not found in the members of the object, but in the data This field exists in the other 1 object returned within; And data Returned in the now It's not really .app > p0 , but this.now The initial value of the data Medium setInterval Modify now Can't update the rendering time; If you want to reuse this data and its update logic, you must write a separate copy of this structure, and then pass it through a special mixin Function is mixed into the construction parameters of the current component.

This 1 cut is because the whole module default The object is actually vm Gets or sets the construction parameters for the. The object creation logic is hidden behind it. When constructing the object, 1 different levels of fields in the construction parameters are bound to the vm Object.

Many novices may have made a mistake, in data And the data fields returned in the props , methods Or computed The field named crash in (especially using the field named data) cannot be directly detected by IDE during the coding stage. Because of the above, these fields belong to different locations when they are created, and are tied to the same object when they are constructed later, resulting in conflicts that can only be discovered at runtime.

In Vue3, change to provide ref , reactive , toRef , onMounted And other functions in the form of implementation, in the example:

In setup What you see in now That is, for binding this.now ; Modify setup0 You can see the update of page status; If you want to encapsulate this data processing, just set the now And onMounted Processing is extracted into the same function, and then the now You can return, and you no longer need a black box mixin Handle.

It can be said that Vue3 directly gives the decision-making power of response data creation and the notification callback of life cycle to developers in the form of API, which is more intuitive, clear and controllable.

4. API Description

Here are some commonly used responsive data correlation API in detail: ref , reactive And toRefs .

(1) ref

The ref used in the above example can wrap 1 piece of data into a responsive data proxy object.


const count = ref(0);
console.log(count.value); // => 0

count.value++;
console.log(count.value); // => 1

When you modify the count. value property of the proxy object, the location where count is used in the template will update the data status in the view in response to the data changes.

(2) reactive

For responsive encapsulation of objects, use the ref Slightly troublesome:


const state = ref({
  count: 0,
});
console.log(state.value.count); // => 0

state.value.count++;
console.log(state.value.count); // => 1

At this time, you can use it instead reactive That is modified as if you were manipulating Field 1 of a normal object count To update the view:


const state = reactive({
  count: 0,
});
console.log(state.count); // => 0

state.count++;
console.log(state.count); // => 1

For proxy objects state Adding a new field can also trigger a view update.

(3) toRefs

Sometimes, the name of the object is too long, and we want to use the internal fields of the object directly in the template, but we can't use deconstruction directly:


import { reactive } from 'vue';

export default {
  setup() {
    const position = reactive({
      x: 0,
      y: 0,
    });
    return {
      //  Mistakes, deconstructed  x, y  There is no responsive proxy. After binding to a template, data changes cannot trigger view updates 
      ...position,
    };
  },
};

In this case, use the toRefs After processing, deconstruct and assign values:


import { reactive, toRefs } from 'vue';

export default {
  setup() {
    const position = reactive({
      x: 0,
      y: 0,
    });
    return {
      ...toRefs(position),
    };
  },
};

But it should be noted that, toRefs Handle only when calling position If the existing field of the position Add a new field, and the view update will not be triggered.

The above is the detailed content of the assembled API (1) of Vue 3.0. Please pay attention to other related articles on this site for more information about Vue assembled API!


Related articles: