SoFunction
Updated on 2025-04-05

Detailed analysis of several easily overlooked parts in Vue documents

Regarding some content in the Vue document that you may not be studying, I have made a small summary. As an experienced fast food, it is not particularly suitable for beginners. There may be some inappropriate things. I hope everyone will give more suggestions.

A mixin that saves the amount of code

Mixin concept: component-level reusable logic, including data variables/lifecycle hooks/public methods, so that it can be used directly in mixed components without repeated redundant logic (similar to inheritance)

How to use:

Create a mixin folder under a public folder pub, and create it under

const mixinTest = {
  created() {
    (`components ${} created`)
  },
  methods: {
    hello() {
      ('mixin method hello')
    }
  }
}
export default mixinTest

Reference the public mix file just now in the component and use

import mixinTest from '../pub/mixin/'
export default {
  data() {
    return {
      name: 'hello'
    }
  },
  mixins: [mixinTest],
  methods: {
    useMixin() {
      ()
    }
  }
}

ps: If you use the() method, it will affect all Vue examples created later, please use with caution!

Pay attention to several characteristics of mixin:

  1. The mixed data variables are shallow merges, and the data within the component is preferred when conflicts are conflicted (custom variables inside the object)
  2. The logic in the mixed lifecycle function will be merged with the lifecycle function logic defined in the component and will be executed first (created/mounted/destroy)
  3. The option of mixing the value as an object will be mixed into an object. After conflict, it will also be given priority to the key name in the component (data/method/components/directives)

Slot content distribution

The concept of slot is introduced: The difference between Vue and React in writing lies in the organization of the elements inside the components and subcomponents. There is no child element in the component for us to access and display (not considering the render function for the time being). Instead, the API is slot

Use scenario definition:

  1. Custom subcomponents have nested HTML or other custom tag components
  2. This custom child component is written in the parent component, and the nested things are also placed in the parent component.
  3. By using <slot></slot> tags in the template of the child component, the effect of rendering nested tags written in the parent component is achieved.
  4. The essence is to put the parent component in the child component and insert it into the child component's position, and multiple tags will be inserted together.
&lt;template&gt;
  &lt;div &gt; 
    &lt;self-component&gt; &lt;!--self-componentRepresents a custom component--&gt;
      &lt;span&gt;12345&lt;/span&gt; &lt;!--Nested tags in parent component--&gt; 
    &lt;/self-component&gt; 
  &lt;/div&gt; 
&lt;/template&gt;
&lt;script&gt;
export default {
  components: [selfComponent]
}
&lt;/script&gt;

&lt;!--self-componentComponent templates--&gt;
&lt;template&gt;
  &lt;div&gt;
    &lt;button&gt;&lt;slot&gt;&lt;/slot&gt;&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  // Only if the subcomponent template has a slot tag, can the rendering reference of the tag written in the custom component be obtained.}
&lt;/script&gt;

Two advanced points of slot feature:

Compilation scope of slot insert content: The scope of distributed content, determined based on the template in which it is located

  1. The specific content is written to determine the scope of the compilation (most of the cases are under the scope of the parent component)
  2. 2.1.0+Add a scope slot, so that the properties of the child component can be exposed to the content written in the child component in the parent component.
  3. The slot tag in the child component can be written directly with custom attributes, and then the tag written in the parent component in the slot is added with the slot-scope attribute.
&lt;!-- Parent component template --&gt;
&lt;child :items="items"&gt;
 &lt;!-- Scope slots can also be named --&gt;
 &lt;li slot="item" slot-scope="props" class="my-fancy-item"&gt;{{  }}&lt;/li&gt;
&lt;/child&gt;

&lt;!-- Subcomponent template --&gt;
&lt;ul&gt;
 &lt;slot name="item" v-for="item in items" :text=""&gt;
  &lt;!-- Here is what is displayed when the parent component refers to the child component but does not write the internal content. --&gt;
 &lt;/slot&gt;
&lt;/ul&gt;

The name attribute of slot specifies the location where the tag is inserted, that is, the named slot in the document (this official document explains it clearly)

  1. The slot written in the template of the child component has a name attribute (<slot name="foo"></slot>)
  2. Write the slot content in the child component in the parent component and specify the slot attribute (<p slot="foo">123</p>)
  3. The content of the parent component will be placed in the correct position according to slot==name.
  4. If the slot attribute is not specified, it will be placed in the anonymous slot by default.

Dynamic Components

Many people have written many Vue projects, but they have never used this feature, so it is necessary to say a few more words.

Dynamic components apply:

  1. Single-page application, the switching of some components does not involve routing, but the components in the page with an area need to be changed.
  2. The changed component parameters are consistent in definitions, such as all dialog boxes, and an object needs to be passed in, but the data structure inside the object is different.
  3. By using the component's is attribute, avoid redundant component code in template and avoid more neat v-if template code.

Methods used (drawing from the documentation):

&lt;keep-alive&gt;
  &lt;component v-bind:is="currentView"&gt;
  &lt;!-- The components are in  (Corresponding component name)Change when changes! --&gt;
  &lt;!-- Inactive components will be cached!It can be preserved or re-rendered --&gt;
  &lt;/component&gt;
&lt;/keep-alive&gt;

Note:

  1. All components that are switched dynamically must be introduced into the parent component. Rendering is dynamic, but introduction is not.
  2. <keep-alive>When wrapping dynamic components, inactive component instances will be cached to improve performance and avoid repeated rendering (keep-alive will not render additional DOM structures)
  3. <keep-alive> has two properties: include and exclude, which are used to specify cached and non-cache components (pass in strings/arrays/regulars)
  4. Another way to avoid re-rendering is to add attribute v-once to the label, which is used to cache large amounts of static content and avoid repeated rendering.

ps:<keep-alive> won't work properly in functional components because they don't have cached instances.

Animation and transition

In fact, many front-end engineers use Vue animations and transitions for the first time through library components, so they didn't dig deeper into this area, and various transition effects and button animations started running. Now let's read the following document and make up for the lesson.

The basic methods for implementing animations on the front end are divided into three types: css3 transition and keyframe/javascript manipulation of dom/using webgl or canvas to implement independently. The third one is used as a display animation, which is less combined with interaction. Vue, as a framework, supports animations based on the first two, which can be seen from the four support mentioned in the official documents. However, the official document explains from the two aspects of DOM transition and state transition. The former is the changes in attributes such as the disappearance of the DOM and the appearance of the animation, while the latter is the changes in certain values ​​on the page.

Changes in DOM properties

If it is the manifestation and implicitness of a single element/component, wrap a layer of <transition></transition> outside the component, and then choose whether to be a css transition or a javascript transition.

CSS Transition:

  1. vue provides six style suffixes, essentially adding and deleting corresponding classNames dynamically during the dom transition. (-[enter|leave]-?[active|to]?)
  2. If you use the css library to assist in development, you can define a custom transition class name on the transiton tag, which also has six attributes. ([enter|leave]-?[active|to]?-class)
  3. A common effect is the animation of the element's first rendering. If you lazy load the picture and fly in, you need to add appear to the transiton tag. There are three other attributes to specify (appear-?[to|active]?-class)
&lt;!-- EachCSSThe corresponding animation libraryclassNaming rules may be different,So you have to write it yourself according to the different libraries,Take as an example --&gt;
&lt;transition
  name="custom-classes-transition"
  enter-active-class="animated tada"
  leave-active-class="animated bounceOutRight"
  :duration="{ enter: 500, leave: 800 }"
&gt;...&lt;/transition&gt;
&lt;!-- durationProperties can pass an object,Customize the duration of entry and exit--&gt;

JS Transition:

  1. Because many animation libraries now require engineers to call the functions provided by the library to pass the dom element in for processing, this method is needed at this time
  2. By adding listen events to the transiton tag, there are 8 totals ([before|after]?-?[enter|leave]-?[cancelled]?)
  3. The first parameter of the callback function that listens to the event is el. It is a transition dom element. In the enter and leave, done will be passed as the second parameter.
  4. An animation that the element is rendered for the first time, there are 4 listening events that can be specified ([before|after]?-?appear and appear-cancelled)
&lt;template&gt;
  &lt;transition v-bind:css="false"
  v-on:before-enter="beforeEnter" v-on:enter="enter"
  v-on:leave="leave" v-on:leave-cancelled="leaveCancelled"&gt;
    &lt;!-- For use only JavaScript Transitional element addition v-bind:css="false",Vue Will skip CSS Testing --&gt;
  &lt;/transition&gt;
&lt;/template&gt;
&lt;script&gt;
methods: { // Take Velocity library as an example  beforeEnter: function (el) {/*...*/},
 // This callback function is an optional setting enter: function (el, done) {
  // Velocity(el, { opacity: 1, fontSize: '1.4em' }, { duration: 300 })
  done() //The callback function done is required.  Otherwise, they will be called synchronously. },
 leave: function (el, done) {
  // Velocity(el, { translateX: '15px', rotateZ: '50deg' }, { duration: 600 })
  done()
 },
 leaveCancelled: function (el) {/*...*/}
}
&lt;/script&gt;

Multi-element transition is actually a sentence: use v-if/v-else as usual and add a key to the same label to identify it.

Vue has queue processing for this multi-element animation. This is the mode attribute on the transiton tag. By specifying the (in-out|out-in) mode, the queue effect of disappearing and appearing animations is achieved, making the animation more natural.

<transition name="fade" mode="out-in">
 <!-- ... the buttons ... -->
</transition>

Multi-component transition is also a saying: Use the dynamic components mentioned in the previous section to complete it.

For list transitions, its essence is still the simultaneous transition of multiple elements, but most of the lists are rendered dynamically through arrays, so there are unique aspects, but the overall animation idea remains unchanged. There are some specific points

  1. Use the transitoin-group component, which needs to be rendered as a real element, which can be specified through the tag attribute.
  2. Each element of the list needs to provide a key attribute
  3. If you use CSS to transition, you should consider that the positioning of relevant elements has changed during the change of the list content. If you want to make the positioning an animation of smooth transition, you need another v-move attribute. This property is to set the style of a css class to create the transition of the element when positioning changes. Vue implements an animation queue through FLIP. Just note that the transition element cannot be set to display:inline. Here, the code on the document needs to make a short demo: (In fact, by setting the transition transition attribute on Li, you can also achieve the effect of v-move)
<template>
  <button v-on:click="shuffle">Shuffle</button>
  <transition-group name="flip-list" tag="ul">
    <li v-for="item in items" v-bind:key="item">{{ item }}</li>
  </transition-group>
</template>
<script>
import _ from 'lodash';
export default {
  data() {
    return {
      items: [1,2,3,4,5,6,7,8,9]
    }
  },
  methods: {
    shuffle: function () {
       = _.shuffle()
    }
  }
}
</script>
<style lang="css">
.flip-list-move {
 transition: transform 1s;
}
</style>

Dynamic changes in values ​​and attributes

This part of the animation is mainly aimed at the special effects of the data element itself, such as the addition and decrease of numbers, the transition process control of colors, the implementation of svg animation, etc., which are essentially changes in numbers/text. My own summary is: by using Vue's responsive system, the changes in numbers can be used to create continuous effects on the DOM through external libraries. For example, 1->100 is a continuous process of increasing numbers, and a black->red process. The official document mainly uses several sample codes to illustrate, and its essential steps are as follows:

  1. Modify a variable a through input's two-way binding on the page, and also a variable b that handles the transition effect on the dom
  2. This data is bound by the watcher (a property in the watch object is this variable a), triggering the logic
  3. The logic in the watcher is to specify the initial value b and the final value a through the external transition library, which is to change the value of b to a
  4. The variable bound on the DOM is b. If some complex situations may be based on the computational properties of b, the change process of b is displayed.

After following the above idea, you can complete a unit-level animation effect. This kind of similar process is actually a very common requirement, so it is necessary to encapsulate this process into a component, exposing only the value to be transitioned as an entry. Each time you change this value, it is an animation transition effect. Component encapsulation requires adding the mounted life cycle specified initial value based on the above four steps. At the same time, the original two values ​​a/b are used as a value in the component, and can be distinguished by newValue and oldValue in the watch object. As for the final SVG, its essence is also a transition of numbers, but there are more state variables involved and longer codes. However, there are not many demands for pure front-end pages. However, as a hobby, you can tinker with some fun demos, but the designers must be involved, otherwise those parameters will be difficult to call out.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.