Instruction: a “V -” prefixed feature provided by Vue. When the content of an expression in an instruction changes, the DOM content will change along with it.

V – if instructions

Conditional render instructions to dynamically add or remove DOM elements in the DOM;

Usage Scenarios:

  • Multiple elements show or hide an element by conditional judgment;
  • Switch between two views;

Example:

<script>
window.onload =function(){
    // Create a vue instance
    var app = new Vue({
        el: '#app'.data: {
            type:'C'.loginType:'username'
        },
        methods: {changeloginType(){
                let self = this;
                if(self.loginType=='username'){
                    self.loginType =' '
                }else{
                    self.loginType = 'username'}}}})}</script>

<body>
<div id="app">
    <div style="color:red">V-if's simplicity and utility</div>
    <template>
        <div v-if="type == 'A'"> A </div>
        <div v-else-if="type=='B'"> B </div>
        <div v-else> C </div>
    </template>
    <div style="color:green">V-if switch to the box</div>
    <template v-if="loginType === 'username'">
        <label>User name:</label>
        <input placeholder="Enter your username" key="username-input">
    </template>
    <template v-else>
        <label>Password:</label>
        <input placeholder="Enter your email address" key="email-input">
    </template>
    <button @click="changeloginType">Switch state</button>
</div>
</body>
Copy the code

V-for instruction: circular instruction;

The V-for directive requires a special syntax in the form of site in Sites, which is the source data array, and site, which is an alias for iterating array elements.

V-for can bind data to an array to render a list:

<div id="app">
    <ol>
        <li v-for="site in sites"> {{ site.name }} </li>
    </ol>
</div>
 
<script>
    new Vue({
        el: '#app'.data: {
            sites: [{ name: 'Runoob' }, { name: 'Google'}, {name: 'Taobao'}]}})</script>
Copy the code

Use v-for in the template:

<ul>
    <template v-for="site in sites">
        <li>{{ site.name }}</li>
        <li>--------------</li>
    </template>
</ul>
Copy the code

V – the bind command

Grammar:

<! -- Complete syntax -->
<a v-bind:href="url"></a>

<! - for - >
<a :href="url"></a>
Copy the code

V-bind is used to bind attributes, such as class, style, value, href, etc. You can use v-bind to bind attributes.

Example:

<! -- Bind a property -->
<img v-bind:src="imageSrc">
<! - for - >
<img :src="imageSrc">
<! Inline string concatenation -->
<img :src="'/path/to/images/' + fileName">
<! -- class binding -->
<div :class="{ red: isRed }"></div>
<div :class="[classA, classB]"></div>
<div :class="[classA, { classB: isB, classC: isC }]">
<! -- style binding -->
<div :style="{ fontSize: size + 'px' }"></div>
<div :style="[styleObjectA, styleObjectB]"></div>
<! -- Bind an object with attributes -->
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
<! -- Prop modifier binding DOM properties -->
<div v-bind:text-content.prop="text"></div>
<! -- Prop binding. "Prop" must be declared in my-Component. -->
<my-component :prop="someThing"></my-component>
<! Pass the parent component props to the child component with $props -->
<child-component v-bind="$props"></child-component>
<! -- XLink -->
<svg><a :xlink:special="foo"></a></svg>
Copy the code

(1) Bind HTML Class

Object syntax:

We can pass v-bind:class an object to dynamically switch classes

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

The syntax above indicates that the existence of the active class will depend on the data attribute isActive truthiness.

You can pass more properties into an object to dynamically switch between classes. In addition, the V-bind :class directive can coexist with the ordinary class attribute.

When the following template is available:

<div class="static"
    v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>Data: {isActive: true, hasError: false}Copy the code

The result is rendered as:

<div class="static active"></div>
Copy the code

When isActive or hasError changes, the class list is updated accordingly. For example, if hasError is true, the class list changes to “static Active text- Danger “.

Bound data objects do not have to be defined inline in the template

<div v-bind:class="classObject"></div>
data: {
    classObject: {
        active: true,
        'text-danger': false
    }
}
Copy the code

The rendered result is the same as above. You can also bind a computed property of the returned object here. This is a common and powerful pattern:

<div v-bind:class="classObject"></div>data: { isActive: true, error: null }, computed: { classObject: function () { return { active: this.isActive && ! this.error, 'text-danger': this.error && this.error.type === 'fatal' } } }Copy the code

Array syntax

We can apply a class list by passing an array to V-bind :class

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

data: {
    activeClass: 'active',
    errorClass: 'text-danger'
}
Copy the code

Apply colours to a drawing as follows:

<div class="active text-danger"></div>
Copy the code

Toggle the classes in the list based on the criteria, using a ternary expression

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
Copy the code

Writing this will always add errorClass, but only activeClass if isActive is truthy.

However, this is a bit cumbersome when there are multiple conditional classes. So you can also use object syntax in array syntax

<div v-bind:class="[{ active: isActive }, errorClass]"></div>
Copy the code

(2) Used in components

When the class attribute is used on a custom component, these classes are added to the root element of that component. Classes that already exist on this element are not overwritten.

For example, if you declare this component:

Vue.component('my-component', {
    template: '<p class="foo bar">Hi</p>'})Copy the code

Then add some classes when you use it

<my-component class="baz boo"></my-component>
Copy the code

The HTML will be rendered as:

<p class="foo bar baz boo">Hi</p>
Copy the code

The same is true for classes with data binding

<my-component v-bind:class="{ active: isActive }"></my-component>
Copy the code

When isActive is truthy, HTML will be rendered as

<p class="foo bar active">Hi</p>
Copy the code

(3) Bind inline styles

Object syntax

The v-bind:style object syntax is straightforward — it looks a lot like CSS, but it’s actually a JavaScript object. CSS attribute names can be camelCase or kebab-case delimited (remember to use single quotes) :

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
    activeColor: 'red',
    fontSize: 30
}
Copy the code

It is often better to bind directly to a style object, which makes the template clearer

<div v-bind:style="styleObject"></div>
 
data: {
    styleObject: {
        color: 'red',
        fontSize: '13px'
    }
}
Copy the code

Similarly, object syntax is often used in conjunction with computed properties that return objects

Array syntax

V-bind :style’s array syntax allows you to apply multiple style objects to the same element

<div v-bind:style="[baseStyles, overridingStyles]"></div>
Copy the code

V-on: binds event listening

Event listeners can use the V-ON directive:

<div id="app">
    <button v-on:click="counter += 1">Add 1</button>
    <p>This button has been clicked {{counter}} times.</p>
</div>
 
<script>
new Vue({
    el: '#app'.data: {
        counter: 0}})</script>
Copy the code

Typically, we need a method to call a JavaScript method. V-on can receive a defined method to call.

<div id="app">
    <! -- 'greet' is the method name defined below -->
    <button v-on:click="greet">Greet</button>
</div>
 
<script>
var app = new Vue({
    el: '#app'.data: {
        name: 'Vue.js'
    },
    // Define methods in the methods object
    methods: {
        greet: function (event) {
            // 'this' refers to the current Vue instance in the method
            alert('Hello ' + this.name + '! ')
            // 'event' is a native DOM event
            if (event) {
                alert(event.target.tagName)
            }
        }
    }
})
// You can also call the method directly with JavaScript
app.greet() // -> 'Hello Vue.js! '
</script>
Copy the code

Instead of binding directly to a method, you can also use inline JavaScript statements:

<div id="app">
    <button v-on:click="say('hi')">Say hi</button>
    <button v-on:click="say('what')">Say what</button>
</div>
 
<script>
new Vue({
    el: '#app'.methods: {
        say: function (message) {
            alert(message)
        }
    }
})
</script>
Copy the code

Event modifier

Vue. Js provides event modifiers for V-on to handle DOM event details such as event.preventDefault() or event.stopPropagation().

Vue.js invokes modifiers via an instruction suffix represented by a dot.

  • .stop – Stops bubbling
  • .prevent – Prevents default events
  • .capture – Prevents capture
  • .self – Only listens for events that trigger the element
  • .once – Triggers only once
  • .left – Left button event
  • .right – right-click event
  • .middle – Middle wheel event
<! -- Prevent click events from bubbling -->
<a v-on:click.stop="doThis"></a>
<! Submit events no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>
<! -- modifiers can be concatenated -->
<a v-on:click.stop.prevent="doThat"></a>
<! -- only modifiers -->
<form v-on:submit.prevent></form>
<! Add event listener with event capture mode -->
<div v-on:click.capture="doThis">.</div>
<! Trigger the callback only when the event is triggered on the element itself (not the child elements)
<div v-on:click.self="doThat">.</div>

<! -- Click event can only be clicked once, new in version 2.1.4 -->
<a v-on:click.once="doThis"></a>
Copy the code

Key modifier

Vue allows v-ONS to add key modifiers when listening for keyboard events:

<! Call vm.submit() only if keyCode is 13 -->
<input v-on:keyup.13="submit">
Copy the code

Remembering all the keycodes can be difficult, so Vue provides aliases for the most commonly used keys:

<! - ditto -- -- >
<input v-on:keyup.enter="submit">
<! -- Abbreviated syntax -->
<input @keyup.enter="submit">
Copy the code

Key aliases:. Enter,. TAB,. Delete,. Esc,. Space,. Up,. Down,. Left,. Right,. CTRL,. Alt,. Shift, and. Meta

Example:

<p><! -- Alt + C -->
<input @keyup.alt.67="clear">
<! -- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
Copy the code