search
HomeWeb Front-endJS TutorialDetailed introduction of single file in vue (code example)

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>
        <ul>
            <li>{{item.value}}</li>
        </ul>
    </div>
</template>

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

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

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',
}

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>
        {{content}}
        <el-button>cancel</el-button>
        <el-button>ok</el-button>
    </el-dialg>
</template>

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

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;
};

如上所示,给出的是一个确认弹框的场景实现。确认弹框在很多用户交互中是一个必须的交互形式。很多组件库也采用上面这种 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
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
总结分享几个 VueUse 最佳组合,快来收藏使用吧!总结分享几个 VueUse 最佳组合,快来收藏使用吧!Jul 20, 2022 pm 08:40 PM

VueUse 是 Anthony Fu 的一个开源项目,它为 Vue 开发人员提供了大量适用于 Vue 2 和 Vue 3 的基本 Composition API 实用程序函数。本篇文章就来给大家分享几个我常用的几个 VueUse 最佳组合,希望对大家有所帮助!

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

聊聊Vue3+qrcodejs如何生成二维码并添加文字描述聊聊Vue3+qrcodejs如何生成二维码并添加文字描述Aug 02, 2022 pm 09:19 PM

Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

Github 上 8 个不可错过的 Vue 项目,快来收藏!!Github 上 8 个不可错过的 Vue 项目,快来收藏!!Jun 17, 2022 am 10:37 AM

本篇文章给大家整理分享8个GitHub上很棒的的 Vue 项目,都是非常棒的项目,希望当中有您想要收藏的那一个。

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何使用VueRouter4.x?快速上手指南如何使用VueRouter4.x?快速上手指南Jul 13, 2022 pm 08:11 PM

如何使用VueRouter4.x?下面本篇文章就来给大家分享快速上手教程,介绍一下10分钟快速上手VueRouter4.x的方法,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools