search
HomeWeb Front-endJS TutorialTips on Vue component development (detailed tutorial)

Tips on Vue component development (detailed tutorial)

Jun 01, 2018 pm 03:21 PM
developSkilldetailed

This article provides you with a detailed analysis of the relevant skills and knowledge points of Vue component development through code examples. Readers in need may refer to it.

Preface

As I near graduation, I wrote a simple personal blog. The project address is click me to visit the project address (please ask for a star by the way). This article is the first in a series of summaries. Next, I will imitate a low-profile version of Element's dialog box and pop-up components step by step.

Text

Vue single file component development

When using vue-cli to initialize a project, you will find that there are A HelloWorld.vue file, this is the basic development model of single-file components.

// 注册
Vue.component('my-component', {
 template: &#39;<p>A custom component!</p>&#39;
})

// 创建根实例
new Vue({
 el: &#39;#example&#39;
})

Next, start writing a dialog component.

Dialog

The basic style of the target dialog component is as shown in the figure:

According to the target style, it can be summarized Out:

  1. The dialog component needs a titleprops to indicate the pop-up window title

  2. The dialog component needs to emit an OK event when the OK button is pressed ( That is, tell the parent component that it is confirmed)

  3. Similarly, the dialog component needs to emit a cancellation event

  4. The dialog component needs to provide a slot to facilitate Custom content

Then, the encoding is as follows:

<template>
 <p class="ta-dialog__wrapper">
 <p class="ta-dialog">
  <p class="ta-dialog__header">
  <span>{{ title }}</span>
  <i class="ios-close-empty" @click="handleCancel()"></i>
  </p>
  <p class="ta-dialog__body">
  <slot></slot>
  </p>
  <p class="ta-dialog__footer">
  <button @click="handleCancel()">取消</button>
  <button @click="handleOk()">确定</button>
  </p>
 </p>
 </p>
</template>

<script>
export default {
 name: &#39;Dialog&#39;,

 props: {
 title: {
  type: String,
  default: &#39;标题&#39;
 },
 },

 methods: {
 handleCancel() {
  this.$emit(&#39;cancel&#39;)
 },

 handleOk() {
  this.$emit(&#39;ok&#39;)
 },
 },
}
</script>

This completes the development of the dialog component. The usage method is as follows:

<ta-dialog 
 title="弹窗标题" 
 @ok="handleOk" 
 @cancel="handleCancel">
 <p>我是内容</p>
</ta-dialog>

At this time, I found One problem, when using v-if or v-show to control the display of the pop-up window, there is no animation! ! ! , looks very stiff. Coach, I want to add animation. At this time, the transition component comes into play. Using the transition component combined with css can create many animations with good effects. Next, enhance the dialog component animation. The code is as follows:

<template>
 <transition name="slide-down">
 <p class="ta-dialog__wrapper" v-if="isShow">
  // 省略
 </p>
 </transition>
</template>

<script>
export default {

 data() {
 return {
  isShow: true
 }
 },

 methods: {
 handleCancel() {
  this.isShow = false
  this.$emit(&#39;cancel&#39;)
 },

 handleOk() {
  this.isShow = true
  this.$emit(&#39;ok&#39;)
 },
 },
}
</script>

You can see that the transition component receives a nameprops, so how to write css to complete the animation? A very simple way, just write two
key class (css className) styles:

.slide-down-enter-active {
 animation: dialog-enter ease .3s;
}

.slide-down-leave-active {
 animation: dialog-leave ease .5s;
}

@keyframes dialog-enter {
 from {
 opacity: 0;
 transform: translateY(-20px);
 }

 to {
 opacity: 1;
 transform: translateY(0);
 }
}

@keyframes dialog-leave {
 from {
 opacity: 1;
 transform: translateY(0);
 }

 to {
 opacity: 0;
 transform: translateY(-20px);
 }
}

It is so simple to develop a good dynamic effect. Note that the name of the transition component is slide-down, and the key className of the animation written is slide-down-enter-active and slide-down-leave-active.

Encapsulate Dialog to make MessageBox

The method of using Element's MessageBox is as follows:

this.$confirm(&#39;此操作将永久删除该文件, 是否继续?&#39;, &#39;提示&#39;, {
 confirmButtonText: &#39;确定&#39;,
 cancelButtonText: &#39;取消&#39;,
 type: &#39;warning&#39;
}).then(() => {
 this.$message({
 type: &#39;success&#39;,
 message: &#39;删除成功!&#39;
 });
}).catch(() => {
 this.$message({
 type: &#39;info&#39;,
 message: &#39;已取消删除&#39;
 });   
});

When I saw this code, I felt so magical. So magical, so magical (exclamation three times in a row). Take a closer look, this component is actually an encapsulated dialog,

#Next, I will also encapsulate such a component. First, let’s sort out our thoughts:

  1. The usage method of Element is this.$confirm. Isn’t this just a matter of hanging it on Vue’s prototype?

  2. Element's then means OK, catch means cancel, just promise.

After sorting out my thoughts, I started coding:

import Vue from &#39;vue&#39;
import MessgaeBox from &#39;./src/index&#39;

const Ctur = Vue.extend(MessgaeBox)
let instance = null

const callback = action => {
 if (action === &#39;confirm&#39;) {
 if (instance.showInput) {
  instance.resolve({ value: instance.inputValue, action })
 } else {
  instance.resolve(action)
 }
 } else {
 instance.reject(action)
 }

 instance = null
}

const showMessageBox = (tip, title, opts) => new Promise((resolve, reject) => {
 const propsData = { tip, title, ...opts }

 instance = new Ctur({ propsData }).$mount()
 instance.reject = reject
 instance.resolve = resolve
 instance.callback = callback

 document.body.appendChild(instance.$el)
})


const confirm = (tip, title, opts) => showMessageBox(tip, title, opts)

Vue.prototype.$confirm = confirm

At this point, you may be wondering what to do As for callback, I actually wrote an encapsulated dialog and named it MessageBox.
In its code, there are two methods:

onCancel() {
 this.visible = false
 this.callback && (this.callback.call(this, &#39;cancel&#39;))
},

onConfirm() {
 this.visible = false
 this.callback && (this.callback.call(this, &#39;confirm&#39;))
},

Yes, it is callback when confirming and canceling . I would also like to talk about Vue.extend, which introduces MessageBox into the code.

Instead of using new MessageBox directly, I use new Ctur because this can define data (not just props), for example:

instance = new Ctur({ propsData }).$mount()

At this time, there is actually no MessageBox on the page. We need to execute:

document.body.appendChild(instance.$el)

If you do this directly, you may find that there is no animation when the MessageBox is opened, but there is animation when it is closed. The solution is also very simple, make it still invisible when
appendChild, and then use code like this:

Vue.nextTick(() => instance.visible = true)

This way there will be animation.

Summary

  1. Achieve good animation through transition and css. Among them, the name of the transition component determines the two key classes for writing css, named [name]-enter-active and [name]-leave-active

  2. Inherit one through Vue.extend The constructor of the component (I don’t know how to say it properly, let’s just say it like this), and then through this constructor, you can customize the related properties of the component (usage scenario: js calls the component)

  3. When js calls a component, in order to maintain the animation effect of the component, you can first document.body.appendChild and then Vue.nextTick(() => instance.visible = true)

The above is I compiled it for everyone, I hope it will be helpful to everyone in the future.

Related articles:

postman json springmvc test batch addition instance

JS and Canvas implement image preview compression and upload function

Two ways for Vue single-page application to reference separate style files

The above is the detailed content of Tips on Vue component development (detailed tutorial). 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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft