Detailed description of the single file in Vue (code example)

Source: Internet
Author: User
This article brings you to the content is about Vue single file in detail (code example), there is a certain reference value, the need for friends can refer to, I hope to help you.

With Vue as the front-end developer of the technology stack, it often works with the front-end building tools for project management. For example, the most commonly used Vue family bucket + webpack program for some medium and large-scale front-end project development. With Webpack, Vue's component advantages are even more obvious, and we can improve development efficiency by building front-end pages in our work practices through a single-file component development approach. There is a question:"What are we writing when we write the Vue single file?" " Many people might answer this: template is responsible for templates, JavaScript is responsible for logic, style is responsible for styles. When answering here, a Vue developer's worldview is largely clear. All we have to do is write the template, JavaScript, style in a single-file component. If it is confined to this, it is clear that we cannot serve our entire development process from the better use of single-file components. Next I will discuss some methodological issues in the development of Vue single file.

Vue Single File Essence

The Vue single file is a file that is named with a specific file name extension .vue . The code is as follows:

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: ' First '},                {key: ' Category ', Valu E: ' Article Classification '},                {key: ' tags ', value: ' Tags '},                {key: ' About ', value: ' About Me '},                {key: ' Links ', Value: ' Links '},< c14/>],        };    },};</script><style>.list-demo {    font-size:14px;} </style>

The code contains Template,script,style. The role of the three is not mentioned here, as the above structure shows a basic file structure of the 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 maintained in the near-maintenance mindset. From the perspective of the reusability of components and the maintainability of the latter, this concept greatly improves the development efficiency of the components. Vue single file, neither JS, nor HTML, nor CSS files, how such files are applied to the page, which is the question that will be mentioned below, how the Vue single file is processed into the resources available on the page.

The process by which the Vue single file is processed

The Vue single file is combined with the Webpack build tool, which is referred to vue-loader for processing in Webpack. As shown below:

{    test:/\.vue$/,    loader: ' Vue-loader ',}

The Vue single file introduced by import or require in the project will be vue-loader processed, and Vue-loader will parse the template in the process and return the processing results in the form of templates, script, style, three different types of files Processed by the next loader. If the components of the single-file component are declared in the parent component, the corresponding item in the components is inserted into the parsed script code. This process starts with the entry file main.js , and all of the dependent single-file components go through this process in turn. Subsequent instantiation of all components will be based on dependencies in the business logic, a process that we often use in development. (Here you can pull a single article detailing the Vue-loader process)

Common posture for single files

Component references in templates

First, the mode of use

Splitting and nesting of components:

    • Divide specific business into smaller components in terms of functionality and post-reuse considerations

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

How to: Introduce subcomponents into the parent component, register in components, add the corresponding component reference templates in the template

This approach is also a common way in the development of single files, where all components are instantiated, and are implicitly embedded in the component's nested relationships and business logic. Developers only need to care about the introduction of components, register the component in the parent component logic, and introduce the component as a label in the parent component's template. The instantiation of the component to be introduced in this process can also be controlled through the V-IF directive in the business logic.

Second, the application scenario

In most scenarios we can develop the component in this way. One feature of this pattern is that the introduction of components is done through component registration and the label of the corresponding component written in the template. The step of introducing a component through a label in a template is essential , and this feature may bring a certain amount of duplication to the developer in some business scenarios.

API-style invocation

API invocation refers to the manual creation of instances of subcomponents that do not require the introduction of component and template label placeholders in the business logic to control the instantiation and display of components in the exposed API.

First, the mode of use

    • The function module provides an entry JS to control all the function logic of the function module under the single file instance

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

Operating 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: ' This is a confirm dialog ',            callback:null,        };    },    methods: {        Handlecancelclick () {            this.callback (' Cancel ');        },        Handleokclick () {            This.callback (' confirm ');        },    },};</script>

Confirm.js

Import vue from ' Vue ', import Confirm from './confirm '; const Confirmconstructor = Vue.extend (Confirm); const CONFIRM = (cont ENT) = {let    confirminstance = new Confirmconstructor ({        data: {            content,        },    });    CONFIRMINSTANCE.VM = confirminstance. $mount ();    ConfirmInstance.vm.visible = true;    Manual insertion of the destination Dom    document.body.appendChild (CONFIRMINSTANCE.VM. $el);    ConfirmInstance.vm.callback = action = {        return new Promise ((resolve, reject) = {          Resolve (action); c12/>});    return CONFIRMINSTANCE.VM;};

As shown above, given is a confirmation of the scene implementation of the box. Confirm that the frame is a necessary form of interaction in many user interactions. Many component libraries also use the API-like component calls above. The caller can implement the reference to the function module simply by invoking the API. This avoids the use of a label placeholder in the template. The implementation principle is the manual takeover of the single-file component instantiation, through the vue.extend to get the component corresponding to the Vue subclass, in the API exposed to the call to instantiate this component. In this process we may also have to complete some component data injection, logically related and manually inserting the component into the destination DOM. Manual injection of the DOM is a great feature of this approach by dynamically injecting the purpose DOM into the API, avoiding the repetitive handwritten component label in the business component template when we invoke the function module in each business component.

Second, the application scenario

    • High functional aggregation, simple logic in the components, single input and output, such as some of the more independent bullet frame

    • Some special custom command development, such as in some special scenarios, can be reused with some single-file components, by instantiating the corresponding Vue subclass of the component in the hook of the instruction, and inserting it into the destination DOM by a specific logic (for example: Element-ui's v-loading)

Differences and commonalities

Commonality: Complete the functional logic of the component by instantiating the corresponding component

Difference: the timing and manner of instantiation are different. The introduction of templates is used to make single-file components available through component registration and label introduction. The introduction of tags solves the problem of Dom placement of subassembly insertions, and developers need not care. API-style single-file components, which manually instantiate components when API calls, require manual control to be inserted into the destination DOM.

Summarize

Vue's single-file component provides a modular development approach to Vue, which essentially derives some of the key properties of Vue, such as life cycle functions, methods,computed, Watch,props, and so on. We can use the above two methods to make a single file component, the purpose of the project to minimize duplication of template code, component decoupling.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.