“This is the 20th day of my participation in the Gwen Challenge.



Setup -CDN import

Instantiate the Vue object EL and data parameters methods Methods Computed attributes Attribute binding V-bind: one-way binding V-html: render into HTML code V-model: two-way binding

Event listener event Click event Mouse event event modifier Key modifier

Dynamically bound class and style bound class object syntax Array syntax bound inline style style

Conditional render v-if instruction V-show instruction

List render V-for instruction

case

Setup -CDN import

<! -- Development environment version, including helpful command line warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
Copy the code

Or:

<! -- Production environment version, optimized size and speed -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
Copy the code

Instantiate the Vue object

El and data parameters

new Vue({
    el:"#vue-app".data: {name:"ccy"}})Copy the code

Among them,

  • El stands for Element and refers to a root element node to obtain
  • Data Is used for data storage

We can use the name data by declarative rendering:

<div id="vue-app">
    <h1>{{ name }}</h1>
</div>
Copy the code

Effect: You can see that an H1 tag is rendered under vue-app, which contains the name in data

Method the methods

Methds stores custom methods that can be used to get data from data, such as this.name:

<div id="vue-app">
	<! -- The contents in double braces are from methods, not data.
	<h1>{{ greeting() }}</h1> 
    <p>{{ name }}</p>
    <p>Job:{{job}}</p>
</div>
Copy the code
new Vue({
    el:"#vue-app".data: {name:"ccy".job:"Web development"
    },
    methods: {greeting:function(){
            return "Good morning " + this.name + "!"}}})Copy the code

Effect:

Computed: Calculates attributes

For any complex (and expensive) logic, you should use computed properties computed property cache vs method: computed properties are cached based on reactive dependencies, and they are reevaluated only if the associated reactive dependencies change

That is, the operation to evaluate a property is performed only when the variables involved in the calculation change, otherwise only the results of the previous calculation are returned: when using methods

<div id="vue-app">
	<h1>Computed attribute computed</h1>
    <button @click="a++">A++</button>
    <button @click="b++">B++</button>
    <p>A - {{a}}</p>
    <p>B - {{b}}</p>
    <p>Age + A = {{addToA()}}</p>
    <p>Age + B = {{addToB()}}</p>
</div>
Copy the code
new Vue({
    el:"#vue-app".data: {age:18.a:0.b:0
    },
    methods: {addToA:function(){
            console.log("addToA");
            return this.age+this.a;
        },
        addToB:function(){
            console.log("addToB");
            return this.age+this.b; }}})Copy the code

Effect: whether you click “A++” or “B++”, the addToA and addToB functions are triggered, printing “addToA” and “addToB”.

If you move addToA and addToB to computed

<! -- Evaluating properties is not a function, cannot write parentheses
<p>Age + A = {{addToA}}</p>
<p>Age + B = {{addToB}}</p>
Copy the code
computed:{
    addToA:function(){
        console.log("addToA");
        return this.age+this.a;
    },
    addToB:function(){
        console.log("addToB");
        return this.age+this.b; }}Copy the code

Effect: hit A++ to trigger only addToA; Click B++ to trigger only the addToB function

Attributes bind

V-bind: one-way binding

Sometimes we need to use variables defined in data in tag attributes, but variables are wrapped in quotes and treated as strings, so they don’t have the desired effect. For example:

<a href="{{ personalBlog }}">Personal Blog Homepage</a>
<! -- Or: -->
<a href="personalBlog">Personal Blog Homepage</a>
Copy the code
/* Instantiates the data argument */ in the Vue object
data: {name:"ccy".job:"Web development".personalBlog:"https://blog.csdn.net/qq_43523725"
}
Copy the code

Effect: The code in quotes is treated as a string and cannot really be clicked to jump to the specified link

At this point, we need to use the V-bind instruction to extract the variable from the quotation marks and match its true meaning

<div id="vue-app">
    <h1>{{ greeting() }}</h1>
    <p>Name:{{name}}</p>
    <p>Job:{{job}}</p>
    <a v-bind:href="personalBlog">Personal Blog Homepage</a>
</div>
Copy the code

V-html: Render to HTML code

If we want to nest an HTML tag inside a string, we need to use the V-HTML directive to parse the code inside the string into HTML code

Example:

/* Instantiates the data argument */ in the Vue object
data: {name:"ccy".job:"Web development".personalBlog:"https://blog.csdn.net/qq_43523725"
}
Copy the code
<div id="vue-app">
    <h1>{{ greeting() }}</h1>
    <p>Name:{{name}}</p>
    <p>Job:{{job}}</p>
    <p v-html=personalBlobTag></p>
</div>
Copy the code

Effect: The variable personalBlobTag is parsed into HTML code and rendered

V-model: bidirectional binding

Usually one side enters and the other side displays, and the two are always the same

Example: bidirectionally bind the value of the input tag to the name variable: the initial value of name is “ccy”, so the default value of the input box is “ccY”; The name also changes when the input enters something else. Label Displays the name variable in real time

<div id="vue-app">
    <h1>Two-way binding</h1>
    <label>{{name}}</label><br>
    <input type="text" v-model=name>
</div>
Copy the code

Effect:

The event

Listen for an event

Basic use:

  • Use v-ON instruction;
  • It is followed by the name of the event and the name of the handler. The handler may not be parenthesized, but the parameter must be parenthesized
  • The V-ON directive can be omitted as @ :
 <! -- < tag V-ON: event =" handler name (parameter)"> Content </ tag >-->
 <button v-on:click="add">Add one year old</button>
 <! -- Parentheses are required when passing parameters -->
 <button v-on:click="reduce(10)">Minus ten</button>
 <! -- V-on: can be omitted to @ -->
 <button @click="reduce(1)">Minus one year old</button>
Copy the code

Example:

Click on the event

No parameter: When the button is clicked, the Add/reduce function is triggered to increase the age by 1 / minus 1

<div id="vue-app">
    <h1>The event first</h1>
    <button v-on:click="add">Add one year old</button>
    <! -- V-on: can be omitted to @ -->
    <button @click="reduce">Minus one year old</button>
    <p>My age is {{age}}.</p>
</div>
Copy the code
new Vue({
    el:"#vue-app".data: {age : 18
    },
    methods: {add:function(){
            this.age ++;
        },
        reduce:function(){
            this.age--; }}})Copy the code

Effect: Click “add one year”, age will increase one year; Click “subtract one year” to subtract one year from age

The arguments:

<div id="vue-app">
    <h1>The event first</h1>
    <button @click="add(1)">Add one year old</button>
    <button @click="add(10)">And at the age of ten</button>
    <button v-on:click="reduce">Minus one year old</button>
    <p>My age is {{age}}.</p>
</div>
Copy the code
new Vue({
    el:"#vue-app".data: {age : 18
    },
    methods: {add:function(value){
            this.age +=value;
        },
        reduce:function(){
            this.age--; }}})Copy the code

Effect:

Mouse events

<div id="vue-app">
    <h1>The event first</h1>
    <div id="show" @mousemove="showXY">
        {{x}},{{y}}
    </div>
</div>
Copy the code
new Vue({
    el:"#vue-app".data: {x:0.y:0
    },
    methods: {showXY:function(event){
            this.x = event.offsetX;
            this.y = event.offsetY; }}})Copy the code

Effect: hover over div#show to display the XY position of the mouse relative to the div, starting at (0,0).

Event modifier

Commonly used are:

  • Stop bubbles:.stop
  • Cancel the default event:.prevent
  • This parameter is valid only once:.once
  • Event modifiers can be used concatenously, such as.stop.prevent, and function superimposed

Example: Cancel the default event of a tag, that is, the page does not jump after clicking a tag:

<a @click.prevent href="https://blog.csdn.net/qq_43523725">My CSDN blog home page</a>
Copy the code

Key modifier

Commonly used are:

  • Match the carriage return trigger:.enter
  • Alt + Enter triggers.alt.Enter
  • Matching Spaces triggers:.space

Example:

<div id="vue-app">
    <h1>The event first</h1>
    <label>Name:</label>
    <input type="text" @keyup.enter="logName">
    <label>Age:</label>
    <input type="text" @keyup.enter="logAge">
</div>
Copy the code
/* methods */
logName:function(){
    console.log("Name entered!")},logAge:function(){
    console.log("Age entered!")}Copy the code

Effect: Enter the first input field, press enter, trigger logName, console output “name entered!” , input the second input box, keyboard hit enter, trigger logAge function, console output “age has been entered!”

Dynamically bind class and style

The binding class

Object syntax

Use the v-bind command to bind the class to the object {class name: true/false}.

<div id="vue-app">
    <h1>Dynamically bind CSS styles</h1>
    <div class="show" v-bind:class="{changeColor:changeColor}"></div>
    <! -- '{changeColor:changeColor}' -- '{changeColor:changeColor}'
</div>
Copy the code
new Vue({
    el:"#vue-app".data: {changeColor:true}})Copy the code
.show {
    width: 100px;
    height: 100px;
    background-color: red;
    border: 2px solid # 000;
}
.changeColor{
    background-color: royalblue;
}
Copy the code

Effect: div.show originally had a red background color (changeColor:false in data)

When changeColor is in effect, the background color is blue (changeColor:true in Data)

Array syntax

You can also pass an array to a class and apply a class list, [class1, class2,… , such as:

<div v-bind:class="[changeColor, addRadiusClass]"></div>
<! -- changeColor is the data in data -->
Copy the code
data: {
  changeColor: 'changeColor'.addRadiusClass: 'change-radius'
}
/* change-radius is the class name and needs to be quoted */
Copy the code
.changeColor{
    background-color: royalblue;
}
.change-radius {
    border-radius: 10px;
}
Copy the code

Effect: Show, changeColor, and change-radius all take effect

You can also use object syntax nested within arrays

<div v-bind:class="[{ changeColor: changeColor }, addRadiusClass]"></div>
Copy the code
data:{
    changeColor:true.addRadiusClass:"change-radius"
}
/* changeColor uses object syntax with a Boolean value. AddRadiusClass uses array syntax with a class name */
Copy the code

The effect is the same as above:

Bind inline style style

Use the V-bind directive to bind the style to the specified style, as in:

<div id="vue-app">
    <h1>Dynamically bound style</h1>
    <div class="show" v-bind:style="styleObject"></div>
</div>
Copy the code
// Style: blue background, rounded 10px
data: {styleObject: {backgroundColor:"blue".borderRadius:"10px"}}Copy the code

Effect:

Conditions apply colours to a drawing

V – if instructions

  • The V-if directive is used to conditionally render a piece of content. This content will only be rendered if the expression of the directive returns true
  • The V-els-if instruction acts as an “else-if block” for v-IF and can be used continuously
  • The V-else instruction, that is, performs the operation if the conditions above are not matched

Example:

<div id="vue-app">
    <h1>Conditions apply colours to a drawing</h1>
    <! -- When type is A/B/C, or other, display different cases respectively -->
    <div v-if="type === 'A'">This is A</div>
    <div v-else-if="type === 'B'">This is B</div>
    <div v-else-if="type === 'C'">This is a C</div>
    <div v-else>
        Not A/B/C
    </div>
</div>
Copy the code
data:{
    type:"A"
}
Copy the code

Effect: Currently type A, only “this is A” div is displayed, other divs are not rendered

V – show commands

When the value of the V-show command is true, the label and contents are displayed

<div id="vue-app">
    <h1>V - show commands</h1>
    <h2 v-show="isShow">hello</h2>
</div>
Copy the code
data:{
    isShow:true
}
Copy the code

Effect: isShow is true to display the label

Display: None when isShow is false

In general, V-if has a higher switching overhead, while V-show has a higher initial rendering overhead. Therefore, v-show is good if you need to switch very frequently; It is better to use V-if if conditions rarely change at run time.

The list of rendering

V – for instructions

Iterate over a set of or objects or integers to iterate over their values

<div id="vue-app">
    <h1>The list of rendering</h1>
    <ul>
        <! --> < span style = "max-width: 100%; clear: both;
        <li v-for="item in arrItems" v-bind:key="item.id">{{ item }}</li>
    </ul>
    <ul>
        <! -- Traverse the object -->
        <li v-for="item in objItems" v-bind:key="item.id">{{ item }}</li>
    </ul>
    <ul>
        <! -- Iterate over json objects -->
        <li v-for="item in jsonItems" v-bind:key="item.id">{{ item.name }} -- {{item.summarize}}</li>
    </ul>
</div>
Copy the code
data:{
    arrItems: ["Vue"."React"."Angular"].objItems: {"name":"ccy"."job":"Web development"."descript":"under studying"
    },
    jsonItems:[
        {"name":"Vue"."summarize":"Progressive JavaScript Framework"},
        {"name":"React"."summarize":"JavaScript libraries for building user interfaces"},
        {"name":"Angular"."summarize":"A development platform built on TypeScript"}}]Copy the code

Effect:

case

Effect: Click the button to display a different picture

Step by step:

Technical points of 4 pictures display: dynamic binding style is adopted

<div v-bind:style="imgStyle">
    <img :src="imgsrc" alt="">
</div>
Copy the code

Technical point: V-for is adopted

<div class="styleObject">
    <div v-bind:class="{text:true}" v-for="item in items" v-bind:key="item.id">
        {{item}}
    </div>
</div>
Copy the code

“Spring, summer, Autumn and Winter” 4 button technical points: dynamic binding style, V-for, click event (parameter transfer)

<div id="season">
    <button v-bind:class="{liStyle:true}"  v-for="(season,index) in seasons" v-bind:key="season.id" @click="changeImage(index)">
        {{season.name}}
    </button>
</div>
Copy the code

Separately extract the data required by the case:

var dataObj = {
	// Spring, summer, autumn and winter
    season:[
        {'name':'spring'},
        {'name':'summer'},
        {'name':"Autumn"},
        {'name':'winter'},].// 4 image addresses
    imgAddress:[
        {src:"./imgs/1-0.jpg"},
        {src:"./imgs/1-2.jpg"},
        {src:"./imgs/1-1.jpg"},
        {src:"./imgs/1-3.jpg"}}]Copy the code

Vue instance object:

/* * items: store "enthusiastic, positive, positive" on the right side; ImgStyle: imgStyle; * Seasons: seasons button value; * imgAddress: image address; * imgsrc: initial value of the image, is the corresponding image of "spring"; * changeImage: Click "four seasons" button, will be clicked button index to this function, control display corresponding image */
new Vue({
    el:"#vue-app".data: {items: ["Passion"."向上"."Positive"].imgStyle: {display:"inline-block".width: "300px".height: "300px".textAlign:"center".paddingTop:"40px".borderRadius:"150px"
        },
        seasons:dataObj.season,
        imgAddress:dataObj.imgAddress,
        imgsrc:dataObj.imgAddress[0].src
        },
		methods: {changeImage:function(value){
		        if (value <= this.imgAddress.length-1 && value >=0) {this.imgsrc = this.imgAddress[value].src; }}})Copy the code

Code word is not easy, please advise, welcome to like, comment, favorites, share