Soul Torture: Do you know all the Vue template syntax?

Keywords: Vue Javascript Attribute JQuery

Author| Jeskson

Excavation| https://juejin.im/user/5a16e1f3f265da43128096cb

The founder of Vue.js is Yuyuxi. In 2014, Vue.js was officially released, and in 2015, it was officially released as version 1.00.VUE.JS is a progressive JavaScript framework with declarative rendering, component systems, client routing, centralized state management, and project building.

Vue.js is a progressive framework for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom. The core libraries of vue.js concern only the view layer and are easy to get started with and integrate with third-party libraries or existing projects.

The advantage of vue, easy to use, is that you can quickly get started with vue, flexible, self-scaling between a library and a complete set of frameworks, efficient, file size 20kb running size, providing ultra-fast virtual DOM.

Code for traditional development patterns:

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" src="js/jquery.js"></script>

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

Basic operation of Vue, hello to the world!

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

<script type="text/javascript" src="js/vue.js"></script>

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

The process of using Vue requires that tags be provided to fill in the data, and vue.js library files are introduced, which can use vue's syntax as a function to fill the data provided by Vue into the tags.

el property, where the element is mounted, the value can be a css selector or a dom element

Data attribute, model data, value is an object

Interpolation expression usage

Fill data into HTML tags, and interpolation expressions support basic computational operations

How vue code works

vue grammar to native grammar, the grammar of vue is compiled into native code through the vue framework.

Template syntax for vue

How do you understand front-end rendering?

Fill data into HTML Tags

Templates and Data - "Front End Rendering -" Static HTML File

Front-end rendering: native js stitched strings, using the front-end template engine, using vue-specific template syntax

Native js splicing strings are strings that splice data into HTML tags.

What is an instruction?What is a custom attribute, the essence of an instruction is a custom attribute, and the instruction format begins with v-

Directive v-cloak

There is a problem with the interpolation expression, "flicker" problem, which is the effect of flickering when refreshing. How to solve the problem, use v-cloak instructions to solve the principle of this problem, hide, replace the value before displaying the final value.

V-cloak, no expression required, usage, this directive remains on the element until the associated instance has finished compiling, and when used with css rules such as [v-cloak] {display: none}, this directive can hide uncompiled mustache tags until the instance is ready.

Example: Standard attribute selector

[v-cloak] {
 display: none;
}

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

Will not be displayed until the compilation is complete.

Usage of v-cloak directive

The first step is to use the provided styles

[v-cloak] {
 display: none;
}

The second step is to add the v-cloak directive to the label where the interpolation expression is located

Essentially, content is hidden by styles, then values are replaced in memory, and the final result is displayed.

Data Binding Instructions

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

v-text, string, updates the textContent of the element

Example:

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

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

V-html, string, innerHTML for updated elements, content is inserted as regular HTML, and will not be compiled as a vue template. If you attempt to use v-html composite templates, you can reconsider whether to use components instead.

Dynamically rendering any HTML on a Web site is dangerous and can lead to xss attacks. Use v-html only on trusted content and never on user-submitted content.

In single-file components, scopeds'styles are not applied inside v-html because that part of HTML is not handled by vue's template compiler. If you want to set scoped css for v-html's content, you can replace it with css modules or manually set bem-like scoping policies with an additional global <style>element.

v-html fills in HTML fragments. If there are security problems, the data can only be used within this site, but not by third parties.

V-prepopulate raw information

What is the raw information, that is, if so, skip the compilation process without compiling

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

Causes the result to be: {{msg}}

instructions

Data responsiveness, response in HTML5, data responsiveness, what is data binding?v-once will only compile once.Changes in HTML5, changes in screen size can lead to changes in style, and changes in data responsiveness can lead to changes in content on the page.

How data binding is understood is an interpolation expression that fills data into a tag.

Compile, vue's template content is compiled through vue's compilation process, v-once only compiles once, after displaying the content, it no longer has responsiveness.

Bidirectional data binding

Usage of v-model directive

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

MVVM design idea: put different function codes in different modules

M,model
v,VIEW
VM,view-model

The model, the data, the data used, the view, is the combination of the dom elements, the template, the vm, to combine the two.

Core Ideas, Divide and Eat, Event Monitoring, Data Binding.

Event binding, how to handle events, use of v-on instructions

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

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

Calls to event functions

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 Event Bubbles

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

Event modifier

Stop to stop bubbles
 <a v-on:click.stop = "dada">Jump</a>

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

event processing

Listen for events

You can use the v-on directive 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 processors

In addition to binding directly to a method, you can also call 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 event no longer overloads page
<form v-on:submit.prevent="onSubmit"></form>

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

// Modifiers only
<form v-on:submit.prevent></form>

// Use event capture mode when adding event listening
// Events triggered for the element itself are handled here before being handled by the element
<div v-on:click.capture="doThis"></div>

// Only trigger handlers when event.target is the current element itself
// That is, the event is not triggered from an internal element
<div v-on:click.self="doThat">..</div>

Key modifier

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

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

Use modifiers to be aware of the order in which the corresponding code is generated.

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

v-on:click.self.prevent only blocks clicks on the element itself

All key aliases:

.enter

.tab

.delete

.esc

.space

.up

.down

.left

.right

Custom Key Event Modifier

You can customize key modifier aliases 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" src="js/vue.js"></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 example, simple calculator

Requirements, for simple addition calculations, enter values a and b, click the Calculate button, and the results are shown below

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

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

<div>
<span>numerical value b:</span>
<span>
<input type="text" v-model="b">
</span>
</div>

<div>
<button @:click="handle">Calculation</button>
</div>

<div>
<span>Calculation results:</span>
<span></span>
</div>
</div>

<script type="text/javascript" src="js/vue.js"></script>

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

Property Binding

How does vue handle attributes dynamically?

// v-bind directive
<a v-bind:href="url">Jump</a>

// Abbreviations
<a :href="url">Jump</a>

Examine the nature of v-model directives

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

<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">

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

Optimize:

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

Style binding

class style processing

Object Grammar

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

Array syntax

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

Syntax for 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 and array bindings can be used in combination, and class-bound values can simplify operations.

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

// Object simplification
objClass: {
 active: true,
 error: true
}

Style style processing

// Object Grammar
<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 directive is used to conditionally render a block of content.This content will only be rendered if the expression of the instruction returns a truthy value.

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

You can also add an "else block" with v-else:

<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 toggles the display of an element's CSS attribute.

Differences between v-if and v-show

v-if controls whether elements are rendered to the page

Whether the v-show control element is displayed, has been rendered to the page

Cyclic structure

// v-for traversal array
<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>

Role of key: Helps vue distinguish between different elements to improve performance

Use of v-if and v-for

// v-for traversal object
<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 Tab Tab

Main ideas:

Click on different tab s

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

Keep tab content subscripts consistent with tab tab subscripts when clicked

Use v-show / v-if instructions 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, and I also hope that you can support, criticize and correct more articles in the future, so that we can make progress and take the road together.

Thank you very much to the reader for seeing this. If this article is well written, feels like I have something to do with Dada, feels like I can keep on learning, feels like this person can make friends, asks for compliments, asks for attention, asks for sharing, really for a warm man

Very useful!!!

Don't forget to leave a footprint of your study [compliment + collection + comment]

Author Info:

[Author]: Jeskson Original Public Number: Dada Front End Bistro. Welfare: Public Number replies to the big gift package for self-study materials (share in groups, just say anything you want, see if I have one)! [Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

Big Front End Development, Locate Front End Development Technology Stack Blog, PHP Background Knowledge Point, web Full Stack Technology Field, Data Structure and Algorithms, Network Principles and other understandable presentations to small partners.Thank you for your support and love!!!

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Posted by kingconnections on Sat, 04 Jan 2020 08:44:26 -0800