search
HomeWeb Front-endJS TutorialVue documentation use case summary

This time I will bring you a summary of Vue document usage cases. What are the precautions when using Vue documents? The following is a practical case, let’s take a look.

mixin that saves code

mixin concept: component-level reusable logic, including data variables/life cyclehook/ Public methods can be used directly in mixed components without having to repeatedly write redundant logic (similar to inheritance)

Usage method:

Create under a certain public folder pub mixin folder, create mixinTest.js

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

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

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

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

Pay attention to several characteristics of mixin:

  1. The data variables mixed in are shallowly merged. In case of conflict, the data in the component takes precedence (the self- definition in the object Variable)

  2. The logic in the mixed life cycle function will be merged with the life cycle function logic defined in the component and executed first (created/mounted/destroy)

  3. The mixed value is an object option, which will be mixed into an object. After a conflict, the key name within the component will take precedence (data/method/components/directives)

slot content distribution

Slot concept introduction: The difference between Vue and React in writing lies in the organization of internal elements of components and sub-components. There is no The children element is for us to access and display (not considering the render function for the time being). The API instead is slot

Usage scenario definition:

  1. Customized child component There are nested HTML or other custom tag components inside

  2. This custom sub-component is written in the parent component, and the nested things are also placed in the parent component

  3. By using the tag in the template of the child component, the effect of rendering the nested tags written in the parent component is achieved

  4. The essence is to put the content of the parent component in the child component and insert it into the position of the child component. Multiple tags will also be inserted together

<template>
  <p> 
    <self-component> <!--self-component表示自定义的组件-->
      <span>12345</span> <!--父组件里的嵌套标签--> 
    </self-component> 
  </p> 
</template>
<script>
export default {
  components: [selfComponent]
}
</script>
<!--self-component的组件模板-->
<template>
  <p>
    <button><slot></slot></button>
  </p>
</template>
<script>
export default {
  // 只有子组件的模板里面有slot标签,才能取到写在自定义组件里面的标签的渲染引用
}
</script>

slot feature Two points:

The compilation scope of slot inserted content: The scope of the distributed content is determined according to the template where it is located

  1. The location where the specific content is written is determined Compiled scope (in most cases under the scope of the parent component)

  2. 2.1.0 Added a new scope slot, so that the properties of the child component can be exposed to the parent The content written in the sub-component in the component can directly write custom attributes using the slot tag in the sub-component, and then add the slot-scope attribute to the tag written in the slot by the parent component.

  3. <!-- 父组件模板 -->
    <child>
     <!-- 作用域插槽也可以是具名的 -->
     <li>{{ props.text }}</li>
    </child>
    <!-- 子组件模板 -->
    
            

    The name attribute of slot specifies the location where the label is inserted, which is the named slot in the document (this official document makes it clear)

The slot written in the template of the child component has a name attribute ()

  1. Write the child in the parent component For the slot content in the component, specify the slot attribute (

    123

    )
  2. The content of the parent component will correspond to slot==name Place it in the correct location

  3. If the slot attribute is not specified, it will be placed in the anonymous slot by default

  4. Dynamic components

This feature of dynamic components has been written by many people in many Vue projects, but they have never used it. It is necessary to say a few more wordsApplicability of dynamic components:

Single page application, the switching of some components does not involve routing, only the components in an area of ​​the page need to be changed

  1. The definition of the changed component parameters They are consistent, for example, they are all dialog boxes, and an object needs to be passed in, but the data structure in the object is different

  2. By using the is attribute of component, avoid redundant components in the template Code, avoid multiple v-if template code to be cleaner

使用的方法(借鉴文档):

<keep-alive>
  <component>
  <!-- 组件在 vm.currentview (对应组件名称)变化时改变! -->
  <!-- 非活动组件将被缓存!可以保留它的状态或避免重新渲染 -->
  </component>
</keep-alive>

注意点:

  1. 动态切换的组件都要引入到父组件中,渲染是动态的,但引入不是。

  2. 包裹动态组件时,会缓存不活动的组件实例,提高性能,避免重复渲染(keep-alive不会渲染额外DOM结构)

  3. 有include和exclude这两个属性,用于指定缓存和不缓存的组件(传入字符串/数组/正则)

  4. 另一种避免重新渲染的方法是为标签增加属性v-once,用于缓存大量的静态内容,避免重复渲染。

ps:不会在函数式组件中正常工作,因为它们没有缓存实例。

动画与过渡

其实很多前端工程师第一次用Vue的动画和过渡都是通过库组件来做到的,所以对这块没怎么深挖,各种过渡特效和按钮动画就跑起来了,现在就看下文档,补补课

前端实现动画的基本方法分为三种种:css3的过渡和keyframe/javascript操纵dom/使用webgl或者canvas来独立实现,其中第三种是作为展示动画,与交互结合较少,而Vue作为一个框架,其支持动画基是从前两种入手的,从官方文档提到的四种支持就可以看出这一点。不过官方文档是从DOM过渡和状态过渡两个方面来讲解,前者是DOM的消失和出现的动画等属性的变化,后者是页面上某些值的变化。

DOM属性的改变

若是单个元素/组件的显隐,在组件外面包裹一层,而后选择是css过渡还是javascript过渡

CSS过渡:

  1. vue提供了六个样式后缀,本质是在dom过渡的过程中动态地添加和删除对应的className。(-[enter|leave]-?[active|to]?)

  2. 如果用css库来辅助开发,可以在transiton这个标签上定义自定义过渡类名,也是六个属性。([enter|leave]-?[active|to]?-class)

  3. 常见的一种效果是元素首次渲染的动画,如懒加载图片飞入,这个时候要在transiton标签上加上appear,另有三个属性可指定(appear-?[to|active]?-class)

<!-- 每种CSS动画库对应的class命名规则可能不同,所以根据不同库要自己写,以animate.css为例 -->
<transition>...</transition>
<!-- duration属性可以传一个对象,定制进入和移出的持续时间-->

JS过渡:

  1. 因为现在很多动画库需要工程师调用库提供的函数,把dom元素传入进行处理,这个时候需要这种方式

  2. 通过在transiton这个标签上添加监听事件,共8个([before|after]?-?[enter|leave]-?[cancelled]?)

  3. 监听事件的回调函数的第一个参数都是el,为过渡的dom元素,在enter和leave这两个还会传入done作为第二个参数

  4. 元素首次渲染的动画,可以指定的监听事件有4个([before|after]?-?appear和appear-cancelled)

<template>
  <transition>
    <!-- 对于仅使用 JavaScript 过渡的元素添加 v-bind:css="false",Vue 会跳过 CSS 的检测 -->
  </transition>
</template>
<script>
methods: { // 以Velocity库为例
  beforeEnter: function (el) {/*...*/},
 // 此回调函数是可选项的设置
 enter: function (el, done) {
  // Velocity(el, { opacity: 1, fontSize: &#39;1.4em&#39; }, { duration: 300 })
  done() //回调函数 done 是必须的。否则,它们会被同步调用。
 },
 leave: function (el, done) {
  // Velocity(el, { translateX: &#39;15px&#39;, rotateZ: &#39;50deg&#39; }, { duration: 600 })
  done()
 },
 leaveCancelled: function (el) {/*...*/}
}
</script>

多元素过渡其实就是一句话:照常使用v-if/v-else的同时对同一种标签加上key来标识

Vue对于这种多元素动画有队列上的处理,这就是transiton这个标签上的mode属性,通过指定(in-out|out-in)模式,实现消失和出现动画的队列效果,让动画更加自然。

<transition>
 <!-- ... the buttons ... -->
</transition>

多组件过渡也是一句话:用上一节提到的动态组件,即可完成。

针对列表过渡,其本质仍是多个元素的同时过渡,不过列表大部分是通过数组动态渲染的,因此有独特的地方,不过整体的动画思路不变。具体有以下几点

  1. 使用transitoin-group这个组件,其需要渲染为一个真实元素,可以通过tag这个属性来指定。

  2. 列表的每个元素需要提供key属性

  3. 使用CSS过渡的话,要考虑到列表内容变化过程中,存在相关元素的定位改变,如果要让定位是平滑过渡的动画,要另外一个v-move属性。 这个属性是通过设置一个css类的样式,来将创建元素在定位变化时的过渡,Vue内部是通过FLIP实现了一个动画队列,只要注意一点就是过渡元素不能设置为display:inline,这里需要文档上的代码做一个简短的demo:(其实通过在li上设置过渡transition属性也可以实现v-move的效果)

<template>
  <button>Shuffle</button>
  <transition-group>
    <li>{{ item }}</li>
  </transition-group>
</template>
<script>
import _ from &#39;lodash&#39;;
export default {
  data() {
    return {
      items: [1,2,3,4,5,6,7,8,9]
    }
  },
  methods: {
    shuffle: function () {
      this.items = _.shuffle(this.items)
    }
  }
}
</script>
<style>
.flip-list-move {
 transition: transform 1s;
}
</style>

数值和属性动态变化

这一部分的动画主要是针对数据元素本身的特效,比如数字的增减,颜色的过渡过程控制,svg动画的实现等,其本质都是数字/文本的变化。 我自己总结就是:通过利用Vue的响应式系统,把数字的变化通过外部库把DOM上对应数值的变化做出连续的效果,如1->100是个数字递增的连续过程,黑色->红色的过程。官方文档主要是用几个示例代码来说明,其本质步骤如下:

  1. 在页面上通过input的双向绑定修改某一变量a,还有一个处理dom上的过渡效果的变量b

  2. 这个数据被watcher绑定(watch对象中某个属性是这个变量a),触发逻辑

  3. 在watcher里面的逻辑就是通过外部过渡库,指定初始值b和最终值a,是把b的值最后改为a

  4. DOM上绑定的变量就是b,如果某些复杂情况可能是基于b的计算属性,从而把b的变化过程展现出来

上面这个思路走一遍下来就完成了一个单元级别的动画效果,这种类似的流程其实是很常见的需求,所以有必要把这个过程封装成一个组件,只暴露要过渡的值作为入口,每次改变这个值都是一个动画过渡效果。组件封装需要在上面四个步骤的基础上添加mounted生命周期规定初始值即可,同时原来的两个值a/b在组件里面作为一个值,可以用watch对象中的newValue和oldValue作为区分。   至于最后的SVG,其本质也是数字的过渡,只不过里面涉及的状态变量更多,代码更长而已,不过纯前端页面这种需求倒还是不多的,不过作为爱好倒可以鼓捣一些好玩的小demo,不过肯定需要设计师的参与,要不那些参数可不好调出来呐。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Angular CLI进行Build与Serve步骤说明

Angular CLI进行单元与E2E测试步骤详解

The above is the detailed content of Vue documentation use case summary. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)