Vue foundation

  Front end, Front end frame, vue.js

examineOriginal site, more expanded content and better reading experience!

Vue foundation

Root instance of constructor Vuenew Vue({})And start the Vue application.

var app = Vue({
    el: "#app",
    data: {},
    methods: {}
});

VariableappOn behalf of this Vue instance.

Among them, the essential options areelA that specifies a DOM element that already exists in a page to mount a Vue instance, which can beHTMLElement, or CSS selectors.

var app = Vue({
    el: document.getElementById('app')
});
    

After the mount is successful, you can use theapp.$elAccess this element. Vue provides many commonly used instance properties and methods, all of which are based on$The beginning.

dataOption is used to declare data that requires bidirectional binding within the application. It is recommended that all data to be used should be available in advancedataInternal statement, improve the maintainability of the business.

Vue instancenew Vue({}), which can be used hereappActingdataAll properties in the object can be accessed as followsdataData in:

console.log(app.name);

In addition to explicitly declaring data, it can also point to an existing variable, and a two-way binding is established between them by default. When any one is modified, the other will also change accordingly.

var myData = {
    a: 1
};

var app = Vue({
    el: "#app",
    data: myData
});

app.a = 2;
console.log(myData.a);//2
myData.a = 3;
console.log(app.a);//3

Life cycle

Vue’s Lifecycle Hook:

  • created: Called after the instance is created. Data observation is completed at this stage, but not mounted.$elNot yet available. (This is useful when initialization is required to process some data)
  • mountedelCalled after being mounted on the instance, the first business logic starts here.
  • beforeDestroy: Called before the instance is destroyed. Mainly untie some useaddEventListenerMonitoring events, etc.

These hooks are associated withelAnddataSimilarly, it is also written into Vue instance as an option and hookedthisPointing to the Vue instance that called it.

Interpolation and Expression

Use (Mustache syntax){{}}Is the most basic text interpolation method, it will automatically display our two-way bound data in real time.

v-htmlDirectly output HTML instead of parsed plain text.

<div id="app">
<span v-html="link"></span>
</div>

new Vue({
    el: "#app",
    data: {
        link: '<a href="#">this is a link.</a>'
    }
});

Link’s content will be rendered into aaTags, not plain text.

If user-generated content is usedv-htmlAfter the output, it may lead to XSS attack, so to process the content submitted by the user at the server, you can generally<>Escape.

If you want to display{{}}Label, without replacement, usev-preYou can skip the compilation of this element and its child elements.

  • In{{}}In addition to simple binding attribute values, JavaScript expressions can also be used for simple operations, ternary operations, etc.
  • Vue supports only a single expression, not statements and process control.
  • User-defined global variables cannot be used in expressions, only global variables in Vue whitelist can be used, for exampleMathAndDate.

Filter

Vue.js supports{{}}Add a pipe character to the end of the interpolation(|)Filter data, often users format text, such asAll letters are capitalizedCurrency thousands are separated by commasWait. The filtering rules are customized by adding options to Vue instancesfilterTo set.

<div id="app">
    {{date | formatDate}}
</div>

Filters can also be connected in series and can receive parameters:

<!--串联-->
{{message | filterA | filterB}}

<!--接收参数-->
{{message | filterA('arg1','arg2')}}

Filters should be used to handle simple text transformations, and if more complex data transformations are to be implemented, computational properties should be used.

Command event

Instruction (Directives) is the most commonly used function in Vue.js templates, which is prefixed withv-. The main responsibility of an instruction is to apply certain behaviors to the DOM when the value of its expression changes.

v-bindThe basic purpose of is to dynamically update attributes on HTML elements, such asidclassWait.

Another very important instruction isv-onA used to bind event listeners.

On common elements,v-onYou can listen for native DOM events exceptclickThere are alsodbclickkeyupmousemoveWait. An expression can be a method name, and these methods are written in Vue citymethodsProperty and is in the form of functions whosethisPointing to the current Vue instance itself, it can be used directly.this.xxxTo access or modify data in the form of.

Vue.js willmethodsIn the method of proxy, can like access Vue data call method:

<div id="app">
    <p v-if="show">这是一段为本</p>
    <button @click="handleClose">点击隐藏</button>
</div>

new Vue({
    el: "#app",
    data: {
        show: true
    },
    methods: {
        handleClose: function () {
            this.close()
        },
        close: function () {
            this.show = false
        }
    }
});

InhandleCloseThrough the method directlythis.close()Calledclose()Function.

var app = new Vue({
    el: "#app",
    data: {
        show: true
    },
    methods: {
        init: function (text) {
            console.log(text);
        },
    },
    mounted: function () {
        this.init('在初始化时调用');
    }
});
app.init('通过外部调用');

syntactic sugar

Grammatical sugar refers to adding a method to achieve the same effect without affecting the function, thus facilitating program development.

Vue.jsv-bindAndv-onInstructions all provide grammatical sugar, or abbreviations, such asv-bindAbbreviated as:, mostly foraimgLabel;v-onAbbreviated as@ForinputbuttonLabel.

Calculation attribute

All calculated attributes are written in Vue instances as functionscomputedOption, finally return the calculated results.

Usage of computed attributes

All kinds of complicated logic can be completed in a calculation attribute, including operations, function calls, etc., as long as a result is finally returned.

The calculation attribute can also depend on the data of multiple Vue instances. As long as any data changes, the calculation attribute will be re-executed and the view will be updated.

Each computed attribute contains agetterAnd onesetter.

In most cases, only the default will be usedgetterThe method reads a calculation attribute, which is rarely used in businesssetter, so when you declare a calculated attribute, you can use the default writing method directly. you do not need togetterAndsetterBoth declared.

Besides simple text interpolation, computational attributes are often used to dynamically set the style names of elements.classAnd inline stylesstyle. When using components, computed properties are also often used for dynamic passingprops.

There are also two practical tips for calculating attributes that are easily overlooked:

  1. First, the calculation attribute can depend on other calculation attributes;
  2. Second, the calculation attribute can not only depend on the data of the current Vue instance, but also on the data of other instances.
<div id="app1"></div>
    <div id="app2">
    {{reverseText}}
</div>

var app1 = new Vue({
    el: "#app1",
    data: {
        text: '123,456'
    },
});
var app2 = new Vue({
    el: "#app2",
    computed: {
        reverseText: function () {
            //这里依赖的是实例app1的数据text
            return app1.text.split(',').reverse().join(',');
        }
    }
});

Calculate attribute cache

No calculation attribute is used, inmethodsA method is defined in to achieve the same effect. Even the method can accept parameters and is more flexible to use.

The reason for using a computed attribute is its dependency cache.. When the data on which a calculation attribute depends changes, it will re-take the value. In the above example, as long astextIf the value does not change, the calculation attribute will not be updated. butmethodsIt is different, as long as it is re-rendered, it will be called, so the function will also be executed.

Do you use calculated properties ormethodsDepending on whether you need caching or not, when traversing large arrays and doing a large number of calculations, you should use calculation properties unless you do not want caching.

v-bindAndclassAndstyleBinding

v-bindThe main use of is to dynamically update attributes on HTML elements.

In data binding,v-bindThe two most common applications are the style names of elementsclassAnd inline stylesstyleThe dynamic binding of.

BindingclassSeveral ways of

Object syntax

tov-bind:classSet an object that can be switched dynamicallyclass

<div id="app">
    <div :class="{'active':'isActive'}">测试文字</div>
</div>

new Vue({
    el: "#app",
    data: {
        isActive: true
    },
});

Objects can also be passed in multiple attributes to switch dynamicallyclass. In addition,:classCan be compared with ordinaryclassCoexistence.

<div class="static" :class="{'active':'isActive','error':isError}">测试文字</div>

data: {
    isActive: true,
    isError: false
}

When:classIf the expression of is too long or the logic is complex, you can also bind a calculation property. When there are more than two conditions, both can be useddataOrcomputed.

In addition to calculating attributes, you can also directly bind data of type Object, or use a that is similar to calculating attributes.methods.

Array syntax

When multiple applications are requiredclassYou can use array syntax to:classBind an array, apply anclassList:

<div id="app">
    <div :class="[activeCls,errorCls]">测试文字</div>
</div>

new Vue({
    el: "#app",
    data: {
        activeCls: 'active',
        errorCls: 'error'
    }
});

// 结果
<div class="active error">测试文字</div>

You can also use ternary expressions to switch according to conditionsclass

<div :class="[isActive ? activeCls : '',errorCls]">测试文字</div>

new Vue({
    el: "#app",
    data: {
        isActive: true,
        activeCls: 'active',
        errorCls: 'error'
    }
});

WhenclassWhen there are multiple conditions, you can use object syntax in array syntax:

<div id="app">
    <div :class="[{'active':isActive},errorCls]">测试文字</div>
</div>

Using computation attributes to dynamically set class names for elements is often used in business, especially when writing reusable components, so in the development process,If the expression is long or the logic is complex, the evaluation attribute should be used as preferentially as possible..

Used in Components

If used directly on custom componentsclassOr:class, style rules are applied directly to the root element of this component.

Vue.component('my-component', {
    template: `<p class="article">一些文本</p>`
});

Then when this component is called, the object syntax or array syntax is applied to bind the component.class

<div id="app">
    <my-component :class="{'active':isActive}"></my-component>
</div>

This usage is only applicable to custom components where the outermost layer is a root element, otherwise it will be invalid. When this condition is not met or a class name needs to be set for a specific child element, the of the component should be usedpropsTo deliver.

Binding inline style

Use:styleYou can bind inline styles, methods, and:classSimilarly, there are also object syntax and array syntax, much like writing CSS directly on elements.

<div id="app">
    <div :style="{'color':color, 'fontSize':fontSize+'px'}">文本</div>
</div>

new Vue({
    el: "#app",
    data: {
        color: 'red',
        fontSize: 14
    }
});

The style is usually written indataOrcomputedMedium:

<div id="app">
    <div :style="styles">文本</div>
</div>

new Vue({
    el: "#app",
    data: {
        styles: {
            color: 'red',
            fontSize: 16 + 'px'
        }
    }
});

In actual business,:styleThe array syntax of is not commonly used and can be written in an object, while the more commonly used is to calculate attributes.

In addition, use:styleVue.js will automatically prefix special CSS attribute names, such astransform.

Built-in instruction

Basic instruction

v-cloak

v-cloakNo expression is required, it will be removed from the bound HTML element at the end of compilation of the Vue instance, often with CSSdisplay: none;Cooperate with:

<div id="app" v-cloak>
    {{message}}
</div>

When the network speed is slow and the Vue.js file has not been loaded, it will be displayed on the page{{message}}The DOM will not be replaced until Vue creates the instance and compiles the template, so the process screen will flash. Just add a CSS to solve this problem:

[v-cloak] {
    display: none;
}

V-cloak is a best practice to solve the problem of page flicker caused by slow initialization, which is very practical for simple projects.

In an engineering project, the HTML structure of the project is only emptydivElement, the rest is done by routing and mounting different components, which is no longer needed.v-cloak.

v-once

v-onceIs an instruction that does not require an expression. Its function is to define its element or component to render only once, including all child nodes of the element or component. After the first rendering, it will not be re-rendered with the change of data and will be regarded as static content.

v-onceIt is rarely used in business and may be used if further performance optimization is needed.

Conditional rendering instruction

v-ifv-else-ifv-else

The conditional instruction of Vue.js can render or destroy elements/components in DOM according to the value of expression.

v-else-ifFollow closelyv-if,v-elseFollow closelyv-else-ifOrv-ifWhen the value of the expression is true, the current element/component and all child nodes will be rendered and removed when false.

If more than one element is judged at a time, it can be built in Vue.js<template>A conditional instruction is used on the element, and the final rendered result will not include the element.

Vue is considering efficiency when rendering elements and will reuse existing elements as much as possible instead of re-rendering.

<div id="app">
  <template v-if="type==='name'">
    <label>用户名:</label>
    <input type="text" placeholder="输入用户名">
  </template>
  <template v-else>
    <label>邮箱:</label>
    <input type="text" placeholder="输入邮箱">
  </template>
  <button @click="handleToggleClick">切换输入类型</button>
</div>

new Vue({
  el:"#app",
  data:{
    type:'name'
  },
  methods:{
    handleToggleClick:function(){
      this.type=this.type==='name'?'mail':'name';
    }
  }
})

In the example, after typing the content, click the switch button. Although DOM has changed, what was typed in the input box has not changed but has been replaced.placeholderThe content and description of<input>Elements are reused.

Using Vue.jskeyAttribute allows you to decide whether to reuse elements or not.keyThe value of must be unique.

<input type="text" placeholder="输入用户名" key="name-input">

Give two<input>The elements have all increasedkeyAfter that, it will not be reused. What you type when switching types will also be deleted, however<label>Elements will still be reused because they have not been addedkeyProperty.

v-show

v-showThe usage of andv-ifBasically the same, butv-showIs to change the CSS properties of an elementdisplay.

Whenv-showThe value of the expression isfalseWhen elements are hidden, DOM structural elements are loaded with inline stylesdisplay:none;.

v-showNot in<template>Use on.

v-ifAndv-showThe choice of

v-ifAndv-showIt has similar functions, howeverv-ifIs the real conditional rendering, it will be appropriate according to the expressionDestroy or rebuildElements and bound events or subcomponents.

If the initial value of the expression isfalse, the element/component will not render initially and compilation will only begin when the condition becomes true for the first time.

Andv-showJust a simple CSS property switch, whether the condition is true or not, will be compiled.

In contrast,v-ifIt is more suitable for scenes where conditions do not change frequently, because its switching overhead is relatively large, whilev-showApplicable to frequent switching conditions.

List rendering instructionv-for

Basic usage

List rendering instructions are used when it is necessary to iterate through an array or enumerate an object for circular display.v-for. Its expressions need to be combinedinTo use, similar toitem in itemsThe form of.

List rendering is also supported withofReplaceinAs a delimiter, it is closer to the syntax of JavaScript iterators:

<li v-for="book of books">{{book.name}}</li>

v-forThe expression for supports an optional parameter as the index of the current item.

<li v-for="(book,index) of books">{{index}} - {{book.name}}</li>

SeparatorinBefore the statement using parentheses, the second item isbooksThe index of the current item.

Andv-ifSame,v-forIt can also be used in built-in labels.<template>On, render multiple elements.

In addition to arrays, the properties of objects can also be traversed.

When traversing object properties, there are two optional parameters: key name and index:

<div id="app">
    <ul>
        <li v-for="(value,key,index) of users">
            {{index}} - {{key}} - {{value}}
        </li>
    </ul>
</div>

v-forYou can also iterate over integers:

<div id="app">
    <span v-for="n in 10">{{n}}</span>
</div>

Array update

The core of Vue is the two-way binding of data and views, which includes a set of methods to observe array changes. Using them to change arrays will also trigger view updates:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

Using the above methods will change the original array called by these methods.

The following methods will not change the original array:

  • filter()
  • concat()
  • slice()

They return a new array, and when using these non-mutating methods, the element group can be replaced by the new array.

When Vue detects an array change, it does not directly re-render the entire list, but reuses DOM elements to the maximum. In the replaced array, items with the same elements will not be re-rendered, so you can boldly replace the old array with the new one without worrying about performance.

It should be noted that in the following changed arrays, Vue cannot be detected and view update will not be triggered:

  • Setting items directly by index,app.books[3]={}
  • Modify the array length,app.books.length=1

To solve the first problem, the same effect can be achieved in two ways. The first is built-in Vue.setMethods:

Vue.set(app.books, 3, {
    name: '《CSS秘密花园》',
    author: '无名氏'
});

If you are using componentization in a webpack, Vue is not imported by default, then you can use it.this.$set.

Another method:app.books.splice(3,1,{})

Filtering and sorting

If you don’t want to change the original array and want to filter or sort through a copy of the array, you can use the calculation property to return the filtered or sorted array.

Methods and Events

@click can call a method name without parentheses(), if the method has parameters, the native event object will beeventIncoming.

This design of monitoring events on HTML elements seems to tightly couple DOM and JavaScript, which violates the principle of separation, but in fact it is just the opposite. Because you can know which method is called through HTML, decoupling logic from DOM, which is easy to maintain.

Most importantly, whenviewModelWhen destroying, all the event handlers will be destroyed automatically and need not be handled by themselves.

Vue provides a special variable$eventFor accessing native DOM events.

<div id="app">
    <a href="https://www.apple.com/" @click="handleClick('禁止打开',$event)">打开链接</a>
</div>

Modifier

Vue supports the following modifiers:

  • .stop
  • .prevent
  • .capture
  • .self
  • .once

The specific usage is as follows:

Modifier function Use examples
Prevent click event bubbling <a @click.stop="handle"></a>
Submit events no longer reload pages <form @submit.prevent="handle"></form>
Modifiers can be concatenated <a @click.stop.prevent="handle"></a>
Only modifiers <form @submit.prevent></form>
Use event capture mode when adding event listeners <div @click.capture="handle">...</div>
Callbacks are only executed when the event triggers on the element itself (not a child element) <div @click.self="handle">...</div>
Triggered only once, the component is also applicable. <div @click.once="handle">...</div>

You can also use key modifiers when listening for keyboard events on form elements.

Modifier function Use examples
Only inkeyCodeYes13Called whenvm.submit() <input @keyup.13="submit">

In addition to the specific onekeyCodeIn addition, Vue also provides some shortcut names:

  • .enter
  • .tab
  • .delete(Replenishment “Delete” and “Backspace” Keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

These key modifiers can also be used in combination or with a mouse:

  • .ctrl
  • .alt
  • .shift
  • .meta