Vue template (interpolation, instruction)

1.Mustache

Interpolation {{}}

The most common form of data binding is text interpolation using “Mustache” syntax (double curly braces). Such as:

<span>Message: {{ msg }}</span>
Copy the code

The Mustache tag will be replaced with the value of the MSG attribute (MSG is defined in the data object) on the corresponding data object.

Whenever the MSG property on the bound data object changes, the content at the interpolation is automatically updated.

grammar {{}}JavaScript expression support
Ordinary expression {{ number + 1 }}
Ternary expression {{ ok ? ‘YES’ : ‘NO’ }}
Ternary expression {{ name == ‘smyhvae’ ? ‘true’ : ‘false’ }}
A method is called {{ message.split(”).reverse().join(”) }}

2.v-once

This directive does not need to be followed by any expression indicating that the element is rendered only once and does not change as the data changes.

<h2 v-once>{{message}}</h2>
Copy the code

3.v-html

Note: There is XSS risk that subcomponents will be overwritten

The HTML code in the data is parsed and rendered to the page

<h2 v-html="url"></h2>
Copy the code

4.v-text

V-text works a little bit like Mustache: It’s used to put data in the interface, except that v-text is written in properties and V-text usually takes a string

<h2 v-text="text"></h2>
Copy the code

5.v-pre

The V-pre is used to skip compilation of this element and its children and to show the original Mustache syntax.

<h2 v-pre>{{message}}</h2>
Copy the code

6.v-cloak

In some cases, our browser may simply print the uncompiled Mustache tag. The V-cloak directive, when used with CSS rules, solves the problem of interpolation flickers (i.e. uncompiled tags can be hidden until the instance is ready)

<! At the time of vue parsing, there is no v-cloak attribute at the two sides of the div.<div id="app" v-cloak>
  <h2>{{message}}</h2>
</div>
Copy the code

conclusion

  • Mustache: {{}} syntax, you can write variables/logical expressions/computed values…
  • V-once: Elements are rendered only once and do not change as data changes.
  • V-html =”” : Parses the HTML code in the data and renders it to the page
  • V-text =” MSG “: Write to the property to display the data in the interface
  • V-pre: Original output, showing the original Mustache syntax
  • V-cloak: Used together with CSS rules, it can solve the problem of interpolation flicker

Vue template examples 🌰 : codesandbox. IO/s/vuebaseus…

<template>
  <div>
    <p>Text interpolation {{message}}</p>
    <p>JS expression {{flag? "Yes" : "no"}} (can only be expressions, not js statements)</p>

    <p :id="dynamicId">Dynamic attribute ID</p>
    <p v-html="rawHtml">
      <span>V-html: XSS risk</span>
      <span>[Note] With V-HTML, the child elements are overwritten</span>
    </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "hello vue".flag: true.rawHtml: "Instruction - raw HTML  bold  < I > italic 
        ".dynamicId: `id-${nDate.now()}`}; }};</script>
Copy the code

2. Computed and Watch

  • Computed is cached, and data does not recalculate if it remains unchanged
  • Watch is shallow listening by default, how to deep listening?
  • Watch listen for reference type, oldVal is not available

1.computed Computes attributes

  • The purpose of calculating attributes is to solve the problem that putting too much logic into templates can make them too heavy and difficult to maintain
  • Computed properties are cached based on their reactive dependencies
  • In some cases, we may need to do some transformation of the data before displaying it, or we may need to display multiple data together
    • For example, we havefirstNameandlastNameFor two variables, we need to display the full name.
    • But if we need to display the full name in more than one place, we need to write more than one{{firstName}} {{lastName}}

The computed examples 🌰 : codesandbox. IO/s/vuebaseus…

<template>
  <div>
    <! The purpose of computed properties is to solve the problem that putting too much logic into templates can make templates too heavy and difficult to maintain - computed properties are cached based on their responsive dependencies - in some cases we may need to do some transformation of the data before displaying it. Or you may need to display multiple values together - for example, if we have two variables' firstName 'and' lastName ', we need to display the full name. {{firstName}} {{lastName}} '-->
    <h2>{{ fullName1 }}</h2>
    <h2>{{ fullName2 }}</h2>
    <p>num {{ num }}</p>
    <p>double1 {{ double1 }}</p>
    <input v-model="double2" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 10.firstName: "Her".lastNmae: "Little round face"}; },computed: {
    double1() {
      // Computed has caching, but doubles does not recalculate if data does not change
      return this.num * 2;
    },
    // Depth calculation
    double2: {
      get() {
        return this.num * 2;
      },
      set(val) {
        this.num = val / 2; }},fullName1: function () {
      return this.firstName + "" + this.lastNmae;
    },
    fullName2: {
      set(newVal) {
        console.log("-- set called fullName --");
        console.log("-- set called fullName --", newVal);
        let arr = newVal.split("");
        this.firstName = arr[0];
        this.lastNmae = arr[1];
      },
      get() {
        console.log("-- set called fullName --");
        return this.firstName + "" + this.lastNmae; }},}};</script>
Copy the code

Results:

Methods and computed

  • methodsThe function will be executed whenever it is called, regardless of whether the data has changed or not (sometimes we do not want to call the function when the data has not changed).
  • computedThe calculated properties are cached, and the function is called only once if the data has not changed.

Conclusion:

  • methodsThe function is called regardless of whether the data has changed
  • computedThe function is called back only if the dependent data changes

2. Listener Watch

Application scenarios: Perform asynchronous or expensive operations when data changes (eg: We can use Watch to listen for routes)

Note: The attributes in watch must be existing data in data

Watch examples 🌰 : codesandbox. IO/s/vuebaseus…

// Listeners are used in asynchronous or expensive operations when data changes
// ** * Note **: The property in watch must be the data that already exists in data
<template>
  <div>
    <p>fullName:{{ fullName }}</p>
    <p>FirstName: <input type="text" v-model="firstName" /></p>
    <p>LastName: <input type="text" v-model="lastName" /></p>
    name:<input v-model="name" /> city:<input v-model="info.city" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "Little round face".info: {
        city: "Beijing",},firstName: "Her".lastName: "Little round face".fullName: "Xiao Xue little round face."}; },watch: {
    name(oldVal, val) {
      console.log("watch name", oldVal, val);
      // oldVal and val can be obtained normally
    },
    // Handle is the method that needs to be executed in your watch
    // deep: The depth of the data you want to listen for, usually for changes in an object property
    // immediate: Specifying immediate: true in the option argument triggers the callback immediately with the current value of the expression:
    // info: {
    // handler(oldVal, val) {
    // console.log("watch info", oldVal, val);
    // // watch info {city: "Beijing 11"}{city:" Beijing 11"}
    // // reference type, oldVal not available. Because the Pointers are the same, we're already pointing to a new val
    / /},
    // deep: true, // deep listening
    // //deep means to look deep, the listener will go down layer by layer, adding the listener to all the properties of the object, but the performance overhead will be very high, any modification of any property in OBj will trigger the handler in the listener.
    // },
    // Optimize, we can use string form listener.
    "info.city": {
      handler(oldVal, val) {
        console.log("watch info", oldVal, val);
      },
      immediate: true,},// firstName(val) {
    // // val: indicates the changed value
    // this.fullName = val + " " + this.lastName;
    // },
    // One of the features of watch is that it does not perform the initial binding until firstName changes. What if we wanted to make it perform the change when it was first bound?
    // We need to modify the way we write watch. The modified watch code is as follows:
    firstName: {
      handler(newName, oldName) {
        this.fullName = newName + "" + this.lastName;
      },
      // execute the handler method immediately after declaring firstName in wacth
      immediate: true,},lastName(val) {
      this.fullName = this.firstName + ""+ val; ,}}};</script>
Copy the code

Results:

Class and style

Using dynamic properties

I’ll write it in camel form

How to bind class and style dynamically?

Class and style 🌰 : codesandbox. IO/s/vuebaseus…

Classes can be dynamically bound using object syntax and array syntax:

  • Object syntax: The meaning of object syntax is:classIt’s followed by an object.
  <div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
  <p :class="{ black: isBlack, yellow: isYellow }">Use the class</p>
  
  data: {
    isActive: true.hasError: false.isBlack: true.isYellow: true,
  }
  <style scoped>
      .black {
          background-color: #999;
      }
      .yellow {
          color: yellow;
      }
  </style>
Copy the code
  • Array syntax: Array syntax means:classThis is followed by an array.
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
<p :class="[black, yellow]">Using class (Array)</p>
data: {
  activeClass: 'active'.errorClass: 'text-danger'.black: 'black'.yellow: 'yellow',
}
<style scoped>
    .black {
        background-color: #999;
    }
    .yellow {
        color: yellow;
    }
</style>
Copy the code

Style can also be dynamically bound with object syntax and array syntax:

  • Object syntax:
    • styleThis is followed by an object type
    • The object’skeyIs the name of the CSS property
    • The object’svalueIs the specific assigned value, which can come fromdataThe properties in the
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
<p :style="styleData">Use the style</p>
data: {
  activeColor: 'red'.fontSize: 30
}
Copy the code
  • Array syntax:
    • styleThis is followed by an array type with multiple values separated by,
<div v-bind:style="[styleColor, styleSize]"></div> data: { styleColor: { color: 'red'}, styleSize: {fontSize: '23 px'}, styleData: {fontSize: '40 px, / / into a camel color:' red 'backgroundColor: '# CCC '// convert to hump}}Copy the code

Results:

Four, conditions,

V-if v-else, can use variables, can also use the === expression

What’s the difference between V-if and V-show?

1. Vi -f and V-else -if and v-else

  • Vue’s conditional directives can render or destroy elements or components in the DOM based on the value of an expression
    <h2 v-if="score>=90"> good < / h2 ><h2 v-else-if="score>=80">good</h2>
    <h2 v-else-if="score>=60">Pass the</h2>
    <h2 v-else>Don't pass the</h2>
Copy the code
  • You are not advised to use a large amount of logic in a templatev-if-else-if

2. Reuse element rendering problem

Question: When it comes to Vue, the value of the input is not cleared after the virtual DOM is clicked to switch the form. Why?

  • Introduction: When implemented click button toggleinputForm, we enter onvalueClick the button to switch formsvalueThe values are still there, butinputThe element does switch. Why is that?
<span v-if="isUser">
      <label for="user">The user name</label>
      <input type="text" placeholder="Username" id="user" key="user">
</span>
<span v-else>
      <label for="email">email</label>
      <input type="text" placeholder="Email" id="email" key="email">
</span>
<button @click="isUser=! isUser">Switch type</button>
<script> 
const app = new Vue({
  el: '#app'.data: {
     isUser: true}})</script>
Copy the code
  • The reason:
    • This is because when Vue renders DOM, it tries to reuse existing elements as much as possible for performance reasons, rather than creating new ones
    • In the case above, the Vue does internal comparisons and finds that the two parts are similar and only replaces the attributes, not creates new elements for you
    • If input is no longer used; else input is used directly
  • The solution
    • If we don’t want toVueSimilar reuse problems, can give the correspondinginputaddkey
    • And make sure we get what we needkeyDifferent, this wayvueI’ll create a brand new oneinputThe element

3.v-show

V-show is used very similar to v-if to determine whether an element is rendered or not

  • Compare v-if with V-show
    • V-if When the condition is false, there is no corresponding element in the DOM at all
    • V-show When the condition is false, it simply sets the display attribute of the element to None
  • How do you choose in development?
    • Use v-show when you need to switch between show and hide a lot
    • By using V-if when there is only one switch
<h2 v-show="isShow">{{message}}</h2>
Copy the code

Conditions for example 🌰 : codesandbox. IO/s/vuebaseus…

<template>
  <div>
    <p v-if="type === 'a'">A</p>
    <p v-else-if="type === 'b'">B</p>
    <p v-else>other</p>

    <p v-show="type === 'a'">A by v-show</p>
    <p v-show="type === 'b'">B by v-show</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      type: "a"}; }};</script>
Copy the code

Results:

Loop (list) rendering

  • How do I traverse objects?
  • The importance of key: The key should not be written randomly (e.g. random or index),why?
  • V-for and V-if cannot be used together.

1. V-for traversal number group

  • Action: Generates content by iterating through the specified template content based on the elements in the array.
  • Grammar:v-for="(item, index) in listArr"
<p> Traversal number group </p><ul>
  <! -- item: index: subscript/index -->
  <li v-for="(item, index) in listArr" :key="item.id">
    {{index}} - {{item.id}} - {{item.title}}
  </li>
</ul>
Copy the code

2. V-for traverses the object

  • Action: Traverses an object
  • Grammar:v-for="(value, key, index) in listObj"
<p> Traverse the object </p><ul >
  <! -- value: attribute value key: attribute name index: subscript/index -->
  <li v-for="(val, key, index) in listObj" :key="key">
    {{index}} - {{key}} -  {{val.title}}
  </li>
</ul>
Copy the code

3. The Key attribute in Vue

  • It is officially recommended that we use itv-forAdd one to the corresponding element or component:keyProperties.
  • Why do we need this key property?
    • This is actually the same as Vue’s virtual DOMDiffThe algorithm matters.
    • When a layer has many identical nodes, that is, list nodes, we want to insert a new node
      • We want to be able to add an F between B and C, and the Diff algorithm will run like this by default.
      • Is it inefficient to update C to F, D to C, E to D, and then insert E?
    • So we need to use a key to give each node a unique identity
      • Diff algorithm can correctly identify this node
      • Find the correct location to insert the new node
    • The key’s main purpose is to update the virtual DOM efficiently

When using V-for to update a list of rendered elements, the default is in-place reuse. If the list data is modified, it will determine whether a value is changed based on the key value. If it is changed, it will re-render the item. Otherwise, it will reuse the previous element. We often use index(the index of an array) as the key, but this is not recommended;

4. V – if and v – for

When they are on the same node, v-for has a higher priority than V-if, which means

The V-if will be repeated separately in each V-for loop.

avoidv-ifv-forWith together

  • why

    • If the if judgment is used, the entire list is iterated within the Vue each render, regardless of whether the judgment judgment has changed
  • We tend to do this in two common situations:

    • To filter items in a list (for example, v-for=”user in users” v-if=” user.isactive “). In this case, replace Users with a calculated property (such as activeUsers) and have it return the filtered list.

    • To avoid rendering lists that should be hidden (such as v-for=”user in users” v-if=”shouldShowUsers”). In this case, move the V-if to the container element (such as ul, OL).

    • Details on the official website

5. Array responsive methods

  • Because Vue is responsive, when data changes, Vue automatically detects data changes and the view updates accordingly
  • Vue includes a set of methods to watch arrays compile, and having them change arrays also triggers an update view
    • push()
    • pop()
    • shift()
    • unshift()
    • splice()
    • sort()
    • reverse()

6.Vue.set Modifies responsive data

  • Vue.set(vm.items, indexOftem, newValue)

  • vm.$set(vm.items ,indexOften,newValue)
    Copy the code
    • Parameter 1: The array/object to modify
    • Parameter 2: The index/attribute name to be set
    • Parameter 3: Set value

Six, events,

In front end development, we need to interact with users on a regular basis. At this point, we must monitor the user’s occurrence time, such as click, drag and drop events, etc

  • Event parameter, custom parameter
  • Event modifier, key modifier
  • Where is the event bound to?

Examples of event 🌰 : codesandbox. IO/s/vuebaseus…

<template>
  <div>
    <p>{{ num }}</p>
    <button @click="increment1">+ 1</button>
    <button @click="increment2(2, $event)">+ 2</button>
  </div>
    
  </div>
    
  </form>
  </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 0}; },methods: {
    increment1(event) {
      // eslint-disable-next-line
      console.log("event", event, event.__proto__.constructor); // is a native event object
      // eslint-disable-next-line
      console.log(event.target);
      // eslint-disable-next-line
      console.log(event.currentTarget); // Note that events are registered with the current element, unlike React
      this.num++;

      // 1. Event is native
      // 2. The event is mounted to the current element
      // Same as DOM events
    },
    increment2(val, event) {
      console.log(event.target);
      this.num = this.num + val;
    },
    loadHandler() {
      // do some thing}},mounted() {
    window.addEventListener("load".this.loadHandler);
  },
  beforeDestroy() {
    // [note] VUE bound events are automatically unbound when the component is destroyed
    // Self-bound events need to be self-destructed!!
    window.removeEventListener("load".this.loadHandler); }};</script>
Copy the code

Event modifier

<! -- Prevent the click event from propagating --><a v-on:click.stop="doThis"></a><! -- Submit event not reload page --><form v-on:submit.prevent="onSubmit"></form><! -- modifiers can be concatenated --><a v-on:click.stop.prevent="daThat"></a><! -- only modifiers --><form v-on:submit.prevent></form><! Add event listener in event capture mode, that is, the inner element triggers the event to be processed here, then the inner element to be processed.<div v-on:click.capture="dpThat">.</div><! Trigger handlers only if event.target is the current element itself, i.e. the event is not fired from an internal element.<div v-on:click.self="doThat">.</div>
Copy the code

Key modifier

<! -- Trigger even if Alt or Shift is pressed together --><button @click.ctrl="onClick">A</button><! -- Triggered only when Ctrl is pressed --><button @click.ctrl.exact="onCtrlClick">A</button><! -- triggered when no system modifier is pressed --><button @click.exact="onClick">A</button>
Copy the code

Seven, forms,

1.v-model

The V-model directive is used in Vue to implement bi-directional binding between form elements and data. Data and templates interact, and changes on one side are immediately updated on the other

The difference between V-bind and V-model:

  • v-bind: Only unidirectional data binding can be implemented. Data is automatically bound from M to V.
  • v-model: onlyv-modelTo achieve two-way data binding. Pay attention to,V - after the modelFaces don’t need a colon

Pay attention to

  • v-modelCan only be used in form elements or for custom components. Common form elements include:input(radio,text,address,email...) ,select, checkbox, textarea.

2. V – model principle

  • The V-Model is a syntactic sugar that essentially consists of two operations
    • V-bind binds a value attribute
    • The V-ON directive binds the input event of the current element
  • The following code is equivalent to the following code:
<input type="text" v-model="message"> <! <input type="text" :value="message" @input="message = $event.target.value">Copy the code

3. Modifier lazy number trim

The modifier role
.lazy When the formLose focusOr press theenterWhen,dataThe data in the
.number The input is converted tonumberThe data type
.trim Filter both sides of the contentThe blank space

Form example 🌰 : codesandbox. IO/s/vuebaseus…

<template> <div> <p> Input box: {{ name }}</p> <input type="text" v-model.trim="name" /> <input type="text" v-model.lazy="name" /> <input type="text" V - model. Number = "age" / > < p > multiline text: {{desc}} < / p > < textarea v - model = "desc" > < / textarea > <! <textarea>{{desc}}</textarea> is not allowed. --> <p> Check boxes {{checked}}</p> <input type="checkbox" V-model ="checked" /> <p> Multiple check boxes {{checkedNames}}</p> <input type="checkbox" id="jack" value="Jack" v-model="checkedNames" /> <label for="jack">Jack</label> <input type="checkbox" id="john" value="John" v-model="checkedNames" /> <label for="john">John</label> <input type="checkbox" id="mike" Value ="Mike" V-model ="checkedNames" /> <label for=" Mike" >Mike</label> <p> single {{gender}}</p> <input type="radio" Id ="male" value="male" V-model ="gender" /> <label for="male"> male </label> <input type="radio" ID ="female" value="female" V-model ="gender" /> <label for="female"> female </label> <p> Drop down list select {{selected}}</p> <select V-model ="selected"> <option Disabled value=""> Please select </option> <option>A</option> <option>B</option> <option>C</option> </select> <p> Drop down list select (multiple options) {{ SelectedList}}</p> <select V-model ="selectedList" multiple> <option disabled value=""> Select </option> <option>A</option> <option>B</option> <option>C</option> </select> </div> </template> <script> export default { data() { return { name: Gender: "female", selected: "", selectedList: [],}; }}; </script>Copy the code

Summarize basic Vue usage

This paper examples all 🌰 demo in the following link: codesandbox. IO/s/vuebaseus…

Mainly explained the basic use of VUE:

  1. The template
  2. The computed and watch
  3. Class and style
  4. conditions
  5. cycle
  6. The event
  7. The form

Thank you for reading

Vue components, Vue advanced usage, Vue3 and Vue principle are divided into four articles

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create better articles

Small round face, a focus on the web front – end foundation, engineering, interview front – end public number