Soul torture: do you know all Vue template syntax?

Time:2021-7-16

Soul torture: do you know all Vue template syntax?

By jeskson

Nuggets| https://juejin.im/user/5a16e1…

You Yuxi is the founder of vue.js. In 2014, vue.js was officially released, and in 2015, version 1.00 was officially released. Vue.js is a progressive JavaScript framework with declarative rendering, component system, client routing, centralized state management and project construction.

Vue.js is a set of progressive framework for building user interface. Different from other large frameworks, Vue is designed to be applied layer by layer from bottom to top. The core library of vue.js only cares about the view layer, which is easy to use and integrate with third-party libraries or existing projects.

The advantage of Vue is easy to use, that is, it can start Vue quickly and flexibly, that is, it can be self scalable between a library and a complete framework, with high efficiency, file size of 20KB, running size, and super fast virtual dom.

Code of traditional development mode:

JavaScript native code:

<div id = "msg"> </div>

<script type="text/javascript">
 var msg = 'hello dada';
 var div = document.getElementById("msg");
 div.innerHTML = msg;
</script>

JQuery Code:

<div id="msg"></div>

<script type="text/javascript"></script>

<script type="text/javascript">
 var msg = "hello da";
 $('#msg').html(msg);
</script>

Vue basic operation, say hello to the world!

<div id="app>
 <div>{{msg}}</div>
</div>

<script type="text/javascript"></script>

<script type="text/javascript">
 new Vue({
  el: '#app',
  data: {
   msg: 'hello world'
  }
 })
</script>

In the process of using Vue, you need to provide tags to fill in data. By introducing the vue.js library file, you can use the syntax of Vue to fill the data provided by Vue into tags.

El attribute, the mounting position of the element, and the value can be CSS selector or DOM element

Data property, model data, value is an object

Interpolation expression usage

The data is filled into the HTML tag, and the interpolation expression supports the basic calculation operation

The principle of running Vue code

From Vue syntax to native syntax, Vue syntax is compiled into native code through Vue framework.

The template syntax of Vue

How to understand front end rendering?

Fill data into HTML tags

Template and data front end rendering static HTML file

Front end rendering method: original JS splicing string, using front-end template engine, using Vue’s unique template syntax

The original JS splicing string is to splice data into HTML tags in the form of string.

What is instruction? What is a custom attribute? The essence of an instruction is a custom attribute. The instruction format starts with V –

Instruction v-cloak

There is a problem in the interpolation expression, “flicker” problem, that is, the flicker effect will appear when refreshing. How to solve the problem, use the v-cloak instruction, the principle of solving this problem, first hide, replace the value, and then display the final value.

V-cloak, no expression, usage. This instruction remains on the element until the end of the compilation of the associated instance. When used with CSS rules such as [v-cloak] {display: none}, this instruction can hide the uncompiled mustache tag until the instance is ready.

Example: standard property selector

[v-cloak] {
 display: none;
}

<div v-cloak>
 {{message}}
</div>

It is not displayed until the end of compilation.

Usage of v-cloak instruction

The first step is to use the provided style

[v-cloak] {
 display: none;
}

The second step is to add the v-cloak instruction to the label of the interpolation expression

The essential principle is to hide the content through the style first, then replace the value in the memory, and display the final result after the replacement.

Instructions for data binding

V-text fills in plain text, v-html fills in HTML code, and v-pre fills in original information

V-text, string, update the textcontent of the element

Example:

<span v-text="msg"></span>

<span>{{msg}}</span>

V-html, string, innerHTML of update elements. The content is inserted according to normal HTML and will not be compiled as Vue template. If you try to use v-html combination template, you can reconsider whether to use component instead.

It is very dangerous to render arbitrary HTML dynamically on the website, which is easy to lead to XSS attack. V-html is only used on trusted content and never used on content submitted by users.

In the single file component, scoped style will not be applied in v-html, because that part of HTML is not processed by Vue’s template compiler. If you want to set CSS with scope for the content of v-html, you can replace it with CSS modules or use an additional global compiler<style>Element manually sets a scope policy similar to BEM.

V-html filling HTML fragments, there are security problems, only in the site internal data can be used, third-party data can not be used.

V-pre fills in the original information

What is the original information? If it is, skip the compilation process without compiling

<div v-pre>{{msg}}</div>

The result will be: {MSG}}

instructions

Data responsive, HTML5 responsive, data responsive, what is data binding? V-once compiles only once. Changes in HTML5, changes in screen size will lead to changes in style, data responsiveness refers to changes in the content of the page caused by changes in data.

Soul torture: do you know all Vue template syntax?

How to understand data binding is that interpolation expression is to fill data into label.

To compile, the template content of Vue has to go through the compilation process of Vue. V-once is compiled only once, and no longer has the responsive function after displaying the content.

Bidirectional data binding

Usage of V-model instruction

<input type="text" v-model="name"/>

MVVM design idea: put different function codes into different modules

M,model
v,VIEW
VM,view-model

Model, data, data and view are the combination of DOM element, template and VM, which combine the two together.

Soul torture: do you know all Vue template syntax?

Soul torture: do you know all Vue template syntax?

Soul torture: do you know all Vue template syntax?

The core idea is sharing, event monitoring and data binding.

Event binding, how to handle events, the usage of v-on instruction

<input type="button" v-on:click="num++"/>

<input type="button" @click="num++"/>

Call of event function

Direct binding function name

<button v-on:click="da">dada</button>

Call function

<button v-on:click="da()">dada</button>

Event function parameter passing

Common parameters and event objects

<button v-on:click='da("da",$event)'>da</button>

Prevent events from bubbling

dada: function(event) {
 event.stopPropagation();
}

Event modifier

. stop to prevent bubbling
< a v-on: click.stop = "dada" > jump</a>

. prevent prevents default behavior
< a v-on: Click: prevent = "dada" > jump</a>

event processing

Monitoring events

You can use the v-on instruction to listen for DOM events and run some JavaScript code when triggered.

Example:

<div id="dada">
 <button v-on:click="counter += 1">da da</button>
 <p>dada {{counter}} </p>
</div>

var vm = new Vue({
 el: '#dada',
 data: {
  counter: 0
 }
})

Methods in inline processor

In addition to being directly bound to a method, you can also invoke a method in an inline JavaScript statement.

<div id="da">
 <button v-on:click="say('hi')">dada</button>
</div>

new Vue({
 el: '#da',
 methods: {
  say: function(message) {
   alert(message)
  }
 }
})

Event modifier

Calling event.preventDefault () or event.stopPropagation () in event handlers is a very common requirement.

.stop

.prevent

.capture

.self

.once

.passive
//Prevent click events from continuing to propagate
<a v-on:click.stop = "doThis"></a>

//Submit events no longer overload the page
<form v-on:submit.prevent="onSubmit"></form>

//Modifiers can be concatenated
<a v-on:click.stop.prevent="doThis"></a>

//Only modifiers
<form v-on:submit.prevent></form>

//Use event capture mode when adding event listening
//That is, the event triggered by the element itself is handled here first, and then it is handled by the element
<div v-on:click.capture="doThis"></div>

//Only when the event. Target is the current element itself triggers the handler
//That is, events are not triggered from internal elements
<div v-on:click.self="doThat">..</div>

Key modifier

//. enter enter
<input v-on:keyup.enter="submit">

//. delete key
<input v-on:keyup.deleter="handle">

Pay attention to the order when using modifiers. The corresponding code will be generated in the same order.

V-on: click.prevent.self blocks all clicks

V-on: click.self.prevent only blocks clicking on the element itself

All key aliases:

.enter

.tab

.delete

.esc

.space

.up

.down

.left

.right

Custom key event modifier

You can customize the key modifier alias through the global config.keycodes object

//You can use v-on: Keyup. F1

Vue.config.keyCodes.f1 = 112
<body>
 <div id="app">
  <input type="text" v-on:keyup.aaa="handle" v-model="info">
 </div>
 <script type="text/javascript"></script>
 <script type="text/javascript">
 Vue.config.keyCodes.aaa = 65
 var vm =  new Vue({
  el: '#app',
  data: {
   info: ''
  },
  methods: {
   handle: function(event) {
    console.log(event.keyCode)
   }
  }
 });
</script>

Application examples, simple calculator

Requirements, to achieve a simple addition calculation, respectively, enter the value of a and B, click the calculation button, the results are displayed below

<body> 
<div id="app">
<h1>Calculator</h1>

<div>
<span>Value a</span>
<span>
<input type="text" v-model="a">
</span>
</div>

<div>
<span>Value B:</span>
<span>
<input type="text" v-model="b">
</span>
</div>

<div>
< button @: Click = "handle" > calculate < / button >
</div>

<div>
<span>The results are as follows</span>
<span></span>
</div>
</div>

<script type="text/javascript"></script>

<script type="text/javascript">
 var vm = new Vue({
  el: '#app',
  data: {
   a: '',
   b: '',
   result: ''
  },
   methods: {
    handle: function() {
     //Implementation of computational logic
     this.result = parseInt(this.a) + parseInt(this.b);
    }
   }
 });
</script>

Property binding

How does Vue process attributes dynamically?

//V-bind instruction
< a v-bind: http: // URL "> jump</a>

//Abbreviation method
< A: a</a>

The essence of V-model instruction

<body>
<div id="app">
<input type="text" v-bind:value="msg" v-on:input="handle">
</div>

<script type="text/javascript"></script>
<script type="text/javascript">

var vm = new Vue({
 el:'#app',
 data: {
  msg: 'dada',
 },
 methods: {
  handle: function(event) {
   this.msg = event.target.value;
  }
 }
})

Optimization:

<input type="text" v-bind:value="msg" v-on:input="msg=$event.target.value">

Style binding

Class style processing

Object syntax

<div v-bind:class="{ active: isActive }"></div>

Array syntax

<div v-bind:class="{activeClass, errorClass}"></div>

Syntax of array binding style:

<div v-bind:class="[activeClass, errorClass]'>dada</div>

var vm = new Vue({
 el: '#app',
 data: {
  activeClass: 'active',
  errorClass: 'error'
 },
 methods: {
  handle: function(){
   this.activeClass= '',
   this.errorClass= '',
  }
 }
});

Object binding and array binding can be used together, and class binding values can simplify the operation.

v-bind:class="[activeClass, errorClass, {test: isTest}]"
//Simplification of array
arrClasses: ['active', 'erro'],

//Simplification of objects
objClass: {
 active: true,
 error: true
}

Style processing

//Object syntax
<div v-bind:style=" { color: activeColor, fontSize: fontsize }"></div>

//Array syntax
<div v-bind:style="[baseStyle, overridingStyles]"></div>

Branch loop structure

v-if
v-else
v-else-if
v-show

The V-IF instruction is used to conditionally render a piece of content. This content is only rendered when the instruction’s expression returns the truth value.

<h1 v-if="awesome">Vue is awesome!</h1>

You can also use v-else to add an “else block”:

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

Elements with v-show are always rendered and retained in the dom. V-show simply switches the element’s CSS property display.

The difference between V-IF and v-show

V-IF controls whether the element is rendered to the page

V-show controls whether elements are displayed and rendered to the page

Cyclic structure

//V-for traverses arrays
<li v-for="item in list">{{item}}</li>

<li v-for="(item, index) in list">{{item}}+","+{{index}}</li>

<li :key="item.id" v-for="(item,index) in list">{{item}}</li>

The role of key: help Vue distinguish different elements, so as to improve performance

The use of V-IF and V-for

//V-for traversing objects
<div v-for="(value, key, index) in object"></div>

//V-IF and V-for
<div v-if="value==12" v-for="(value,key,index) in object"></div>

For… In… Loops do not recommend traversing arrays, only objects

example:

Vue implements tab

Main ideas:

Click different tabs

Get the tab subscript and dynamically bind a class (the style when it is selected)

When clicking, make the content subscript corresponding to tab consistent with tab subscript

Using v-show / V-IF command to control content display and hiding

<div class="parts">
    <span @click="func('A');" v-bind:class="{'active':(active=='A') }">A</span>
    <span  @click="func('B');" v-bind:class="{'active':(active=='B') }">B</span>
    <span  @click="func('C');" v-bind:class="{'active':(active=='C') }">C</span>
</div>

<div class="block block1" v-if="block=='A'">
    A block
</div>
<div class="block block1" v-if="block=='B'">
    B block
</div>
<div class="block block1" v-if="block=='C'">
    C block
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            active:'A',
            block:'A'
        },
        filter:{
 
        },
        watch:{
 
        },
        methods: {
            func:function(c){
                this.active=C;
                this.block=C;
            }
        }
    });
</script>
<template id="tp1">
    <div id="nav">
        <ul>
            <li v-for="item in array" @click="choose(item)" :class='content===item?"pink":"blue"'>{{item}}</li>
        </ul>
        <div id="div">{{content}}</div>
    </div>
</template>
<script>
    //Create a component
    var component=Vue.extend({
       template:"#tp1",
        data:function () {
            return{
              Content: "Beijing",
              Array: [Beijing, Shanghai, Hangzhou, Guangzhou, Shenzhen]
           }
        },
        methods:{
           choose:function (item) {
            this.content=item;
           }
        }
    });
    //Register a component
    Vue.component("test",component);
    new Vue({
        el:"#app",
        data:{
            Name: "tab component case"
        }
    });
</script>
<template>
    <div>
      <div id="tab">
        <div class="tab-tit">
          
          <a href="javascript:;" @click="curId=0" :class="{'cur':curId===0}">html</a>
          <a href="javascript:;" @click="curId=1" :class="{'cur':curId===1}">css</a>
          <a href="javascript:;" @click="curId=2" :class="{'cur':curId===2}">javascript</a>
          <a href="javascript:;" @click="curId=3" :class="{'cur':curId===3}">vue</a>
        </div>
        <div class="tab-con">
          
          <div v-show="curId===0">
            html<br/>
          </div>
          <div v-show="curId===1">
            css
          </div>
          <div v-show="curId===2">
            javascript
          </div>
          <div v-show="curId===3">
            vue
          </div>
        </div>
      </div>
    </div>
</template>

In the blog platform, there is still a long way to go in the future. I also hope that we can support and criticize our articles in the future. We can make progress together and make progress together.

Thank you very much for reading this article. If this article is well written, if you think “dada” has something for me, if you think I can persist in learning, if you think this person can make friends, please praise and pay attention ❤️ It’s true for me to share

Very useful!!!

❤️ Don’t forget to leave your footprints [like + collect + comment]

Author Info:

[author]: jeskson
Official account: dada’s front bar.
[welfare]: the official account answers the “information”, sends the gift package of self study materials (enter group to share, want to say anything ha, see if I have).
[reprint description]: please explain the source of reprint, thank you for your cooperation~

Big front-end development, positioning front-end development technology stack, blog, PHP background knowledge points, web full stack technology field, data structure and algorithm, network principle, etc. are presented to small partners easily. Thank you for your support and love!!!


If the content of this number is not in place (such as copyright or other issues), please contact us in time for rectification, and we will deal with it at the first time.


Please like it! Because your approval / encouragement is the biggest driving force of my writing!

Welcome to pay attention to dada’s CSDN!

This is a blog with quality and attitude

Soul torture: do you know all Vue template syntax?