Table of Contents
The essence of vue single file
vue single file processing process
Common postures for single files
Component references in templates
API-style calling
区别和共性
总结
Home Web Front-end JS Tutorial Detailed introduction of single file in vue (code example)

Detailed introduction of single file in vue (code example)

Sep 05, 2018 am 10:12 AM
vue.js

This article brings you a detailed introduction to the single file in Vue (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Front-end developers who use vue as the development technology stack often cooperate with front-end construction tools to carry out engineering management of the project. For example, the commonly used vue family bucket webpack solution is used to develop some medium and large front-end projects. With webpack, Vue's componentization advantages are more obvious. We can build front-end pages in work practice through single-file componentization development, thereby improving development efficiency. There is such a question: "When we write a vue single file, what are we writing?" Many people may answer this way: template is responsible for the template, javascript is responsible for the logic, and style is responsible for the style. When the answer reaches this point, a Vue developer's world view is basically very clear. All we have to do is write template, javascript, and style in a single file component. If we only limit ourselves to this, it is obvious that we cannot serve our entire development process from better utilization of single-file components. Next, I will discuss with you some methodological issues in vue single-file development.

The essence of vue single file

Vue single file is a file named with a specific file extension .vue. The code shown below:

ListDemo.vue

<template>
    <div class="list-demo">
        <ul>
            <li v-for="item in list" :key="item.key">{{item.value}}</li>
        </ul>
    </div>
</template>

<script>
export default {
    name: 'ListNav',
    data() {
        return {
            list: [
                { key: 'home', value: '首页' },
                { key: 'category', value: '文章分类' },
                { key: 'tags', value: '标签' },
                { key: 'about', value: '关于我' },
                { key: 'links', value: '友情链接'},
            ],
        };
    },
};
</script>

<style>
.list-demo {
    font-size: 14px;
}
</style>
Copy after login

The code contains template, script, and style. The functions of the three will not be described in detail here. The above structure shows the basic file structure of a vue single file. The idea behind it is that a single file component corresponds to a functional component, and the template, style, and business logic of the component are all maintained nearby. From the perspective of component reusability and later maintainability, this concept has greatly improved the efficiency of component development. The single file of vue is neither js, html, nor css file. How such a file is applied to the page is a question that will be discussed below. How is the single file of vue processed into the page? Available resources.

vue single file processing process

vue single file cooperates with the webpack build tool and will be processed by vue-loader in webpack. As shown below:

{
    test: /\.vue$/,
    loader: 'vue-loader',
}
Copy after login

The vue single file introduced through import or require in the project will be processed by vue-loader. In this process, vue-loader will parse and process the template according to template, script and style. The results are returned, and three different types of files are handed over to the next loader for processing. If the single-file component is declared in components in the parent component, the corresponding item in components will be inserted into the parsed script code. This process starts from the entry file main.js, and all involved single-file components that are dependent on it go through this process in turn. After that, all components will be instantiated according to the dependencies in the business logic. This process is also a method we often use in development. (You can pull up a separate article here to describe the processing process of vue-loader in detail)

Common postures for single files

Component references in templates

1. How to use

Splitting and nesting of components:

  • Divide specific business into smaller components according to functions and later reusability considerations

  • Integrate small functional components (subcomponents) through a container component (parent component)

Operation method: introduce subcomponents into parent components, components into components Register and add the corresponding component reference template in the template

This method is also a common method we use in single-file development. The instantiation of all components is implicit in the nested relationship of the components. and business logic. Developers only need to care about the introduction of the component, register the component in the parent component logic, and introduce the component as a tag in the template of the parent component. The instantiation timing of the components to be introduced in this process can also be controlled in the business logic through the v-if directive.

2. Applicable Scenarios

In most scenarios, we can carry out component development in this way. This model has a characteristic: the introduction of components is completed through component registration and writing the corresponding component tags in the template. Introducing components through tags in the template is essential. This feature may bring a certain amount of repetitive workload to developers in some business scenarios.

API-style calling

API-style calling refers to manually creating instances of subcomponents. There is no need to introduce components and template tag placeholders in the business logic. Control the components in the exposed API. Instantiation and display.

1. How to use

  • The function module provides an entrance js to control all the functional logic of the order file instance of the function module

  • When using this function module in other components, call the js under the function module and pass in some parameters

Operation method:

Confirm.vue

<template>
    <el-dialg
        title="test"
        :visible.sync="visible">
        {{content}}
        <el-button @click="handleCancelClick">cancel</el-button>
        <el-button @click="handleOkClick">ok</el-button>
    </el-dialg>
</template>

<script>
export default {
    name: 'Confirm',
    data() {
        return {
            visible: false,
            content: '这是一个confirm dialog',
            callback: null,
        };
    },
    methods: {
        handleCancelClick() {
            this.callback('cancel');
        },
        handleOkClick() {
            this.callback('confirm');
        },
    },
};
</script>
Copy after login

confirm.js

import Vue from 'vue';
import Confirm from './confirm';

const ConfirmConstructor = Vue.extend(Confirm);

const confirm = (content) => {
    let confirmInstance = new ConfirmConstructor({
        data: {
            content,
        },
    });
    confirmInstance.vm = confirmInstance.$mount();
    confirmInstance.vm.visible = true;
    // 手动插入目的 dom
    document.body.appendChild(confirmInstance.vm.$el);
    confirmInstance.vm.callback = action => {
        return new Promise((resolve, reject) => {
          resolve(action);
        });
    };
    return confirmInstance.vm;
};
Copy after login

如上所示,给出的是一个确认弹框的场景实现。确认弹框在很多用户交互中是一个必须的交互形式。很多组件库也采用上面这种 API 式的组件调用。调用方仅仅通过 api 的调用,就能实现该功能模块的引用。这样就避免了在 template 中通过标签占位的方式引用。实现原理就是手动接管单文件组件的实例化,通过 Vue.extend 获得该组件对应的 Vue 的子类,在暴露给调用的 api 中去实例化这个组件。这个过程中我们可能还要完成一些组件数据的注入,逻辑相关以及手动将该组件插入到目的 dom 中。手动的注入 dom 是该种方式的一个很大特点,通过在 api 中动态的注入目的 dom,避免我们在各个业务组件中调用该功能模块时重复性的在业务组件 template 中手写组件标签。

二、适用场景

  • 功能聚合度高,组件内逻辑简单,输入输出较为单一,比如一些功能较为独立的弹框

  • 一些特殊的自定义指令开发,比如在一些特殊场景的指令,可以复用一些单文件组件,通过在指令的钩子中实例化组件对应的 vue 子类,按照特定的逻辑插入到目的 dom 中(例如:element-ui的v-loading)

区别和共性

共性:通过实例化对应组件完成组件的功能逻辑

区别:实例化的时机和方式不同。模板式的引入通过组件注册和标签引入的方式来使用单文件组件。标签引入解决了子组件插入的 dom 位置问题,开发者无需关心。API 式的单文件组件使用,在 API 调用时手动实例化组件,需要手动控制插入到目的 dom。

总结

vue 的单文件组件提供了 vue 的组件化开发思路,其本质在导出 vue 的一些关键属性,比如生命周期函数,methods,computed, watch,props等。我们可以通过上述两种方式来使用单文件组件,目的在于工程内部尽量减少重复的模板代码,组件解耦。

相关推荐:

webpack入坑之旅(五)加载vue单文件组件_html/css_WEB-ITnose

jquery加载单文件vue组件方法分享

The above is the detailed content of Detailed introduction of single file in vue (code example). For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles