Home > Web Front-end > JS Tutorial > Detailed introduction of single file in vue (code example)

Detailed introduction of single file in vue (code example)

不言
Release: 2018-09-05 10:12:53
Original
1462 people have browsed it
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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template