Vue -- instruction [learning notes] (continuously updated)

Vue – instruction [learning notes] (continuously updated)

Recorded Vue's study notes on the third day

v-show

Note that v-show does not support < template > elements or v-else.

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

<div id="app">
    <div v-show="shouye">home page</div>
    <div v-show="dongman">comic</div>
    <div v-show="yinyue">music</div>
</div>
let app = new Vue({
    el: "#app",
    data: {
        shouye: true,
        dongman: false,
        yinyue: false,
    }
})

The above execution results will only be displayed on the home page

v-on:click @ Click

Usage 1: write the function name directly in double quotation marks

<div id="app">
    <div v-show="shouye">home page</div>
    <div v-show="dongman">comic</div>
    <div v-show="yinyue">music</div>
    <!-- Note that the function name cannot be the same as the variable name -->
    <button @click="shouYe">home page</button>
    <button @click="dongMan">comic</button>
    <button @click="yinYue">music</button>
</div>
let app = new Vue({
    el: "#app",
    data: {
        shouye: true,
        dongman: false,
        yinyue: false,
    },
    methods: {
        shouYe: function(e){
            // console.log(e);
            this.shouye = true;
            this.dongman = false;
            this.yinyue = false;
        },
        dongMan: function(e){
            this.dongman = true;
            this.shouye = false;
            this.yinyue = false;
        },
        yinYue: function(e){
            this.yinyue = true;
            this.shouye = false;
            this.dongman = false;
        }
    }
})

Click the button to jump to the page

Usage 2: write an expression in double quotation marks

<div id="app">
    <h1>Number of hits:{{ count }}</h1>
    <!-- You can use expressions to complete event operations -->
    <button type="button" @click="count++">Click plus one</button>
</div>
var app = new Vue({
    el: "#app",
    data: {
        count: 0
    }
})

Usage 3: event pass parameter

<div id="app">
    <ul>
        <li v-for="start,index in starts" @click="clickEvent(index,start,$event)">Index value:{{ index }}---Content:{{ start }}</li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        starts: ["Cai Xukun","Fan Bingbing","Li Chen"]
    },
    methods: {
        clickEvent: function(index,start,event){
            console.log(index,start);
            console.log(event);
        }
    }
})

Note: if you want to pass parameters in a function and get an event, you can use $evnet when passing parameters

Usage 4: event modifier

  • stop modifier to prevent bubbling events from passing up
<div id="app">
    <!-- stop Modifier to prevent bubbling events from passing up -->
    <div class="btnParent" @click="clickParent">
        <button @click.stop="clickEvent">Button</button>
    </div>
</div>
var app = new Vue({
    el: "#app",
    data: {

    },
    methods: {
        clickEvent: function(){
            console.log("clickEvent");
        },
        clickParent: function(){
            console.log("clickParent");
        }
    }
})

clickEvent

  • prevent modifier to block default events
<form action="" method="post">
    <input type="text" name="username" id="" value="" />
    <!-- Block default events -->
    <input @click.prevent="searchWeather" type="submit" value="Submit"/>
</form>
<div id="weather">
    <h1>{{ tmp }}</h1>
    <h3>{{ brief }}</h3>
</div>
var app = new Vue({
    el: "#app",
    data: {
		city: "Beijing",
        tmp: "",
        brief: ""
    },
    methods: {
        searchWeather: function(){
            console.log("Query weather");
            console.log(this.city);
            let httpUrl = `https://free-api.heweather.net/s6/weather/now?location=${this.city}&key=3c497450d8e44c5280421ceaba1db581`
            let res = await fetch(httpUrl)
            let result = await res.json();
            console.log(result);
            let now = result.HeWeather6[0].now;
            this.tmp = now.tmp;
            this.brief = now.cond_txt;
        }
    }
})
  • Once modifier, triggered only once
<button type="button" @click.once="onceEvent">A button that triggers only once</button>
var app = new Vue({
    el: "#app",
    data: {
		
    },
    methods: {
		onceEvent: function(){
            console.log("Trigger only once");
        }
    }
})

Trigger only once

  • keydown modifier to specify the key

Note: the form is submitted by pressing enter by default

There are the following keys under keydown

.enter

.tab

. delete (capture delete and backspace keys)

.esc

.space

.up

.down

.left

.right

You can also configure custom modifiers for keys

Vue.config.keyCodes.f1 = 112
<form action="" method="post">
    <input type="text" @keydown.enter="searchWeather" name="username" v-model="city" id="" value="" />
        <!-- Block default events -->
        <input @click.prevent="searchWeather" type="submit" value="Submit"/>
            </form>
var app = new Vue({
    el: "#app",
    data: {
        city: "Beijing",
        tmp: "",
        brief: ""
    },
    methods: {
        searchWeather: function(){
            console.log("Query weather");
            console.log(this.city);
            let httpUrl = `https://free-api.heweather.net/s6/weather/now?location=${this.city}&key=3c497450d8e44c5280421ceaba1db581`
            let res = await fetch(httpUrl)
            let result = await res.json();
            console.log(result);
            let now = result.HeWeather6[0].now;
            this.tmp = now.tmp;
            this.brief = now.cond_txt;
        }
    }
})
  • Exact modifier, exact trigger

Click trigger only after pressing ctrl. If you press other keys and click again, it will not trigger

<button type="button" @click.ctrl.exact="ctrlEvent">Press and hold ctrl click</button>
ctrlEvent: function(){
    console.log("Press and hold ctrl click");
}

v-for

<div id="app">
    <h3>Loop list</h3>
    <ul>
        <li v-for="student in students">
            <h1>full name:{{ student.studentName }}</h1>
            <p>Age:{{ student.age }}---school:{{ student.school }}</p>
        </li>
    </ul>
    <h3>condition+Circular rendering (rendering students of even age),Cycle first and then judge</h3>
    <ul>
        <li v-for="student,index in students" v-if="student.age%2==0" :key="index">
            <h1>Indexes:{{ index }}---full name:{{ student.studentName }}</h1>
            <p>Age:{{ student.age }}---school:{{ student.school }}</p>
        </li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        students: [
            {
                studentName: "Xiao Ming",
                age: 16,
                school: "tsinghua"
            },
            {
                studentName: "Xiao Hei",
                age: 17,
                school: "Peking University"
            },
            {
                studentName: "Xiao Hong",
                age: 18,
                school: "Zhejiang University"
            },
            {
                studentName: "Sakura",
                age: 19,
                school: "River soft"
            },
        ]
    }
})

Calculated (calculated attribute)

The result will be cached as long as this Firstname and this If the contents of the LastName variable do not change, it will not be recalculated

<div id="app">
    <!-- Calculation properties -->
    <div>{{ fullname }}</div>
    <!-- Display 1 word in reverse order -->
    <h1>{{ reverseWord }}</h1>
    <h1>Cyclic even age</h1>
    <ul>
        <li v-for="student in oddStudents">
            <h3>{{ student.studentName }}</h3>
            <h4>{{ student.age }}</h4>
        </li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        firstname: "Zhang",
        lastname: "three",
        word: "music",
        students: [
            {
                studentName: "Xiao Ming",
                age: 16,
                school: "tsinghua"
            },
            {
                studentName: "Xiao Hei",
                age: 17,
                school: "Peking University"
            },
            {
                studentName: "Xiao Hong",
                age: 18,
                school: "Zhejiang University"
            },
            {
                studentName: "Sakura",
                age: 19,
                school: "River soft"
            },
        ]
    },
    computed: {
        fullname: function(){
            // The calculation results will be cached as long as this If the contents of the firstname and lastname variables do not change, they will not be recalculated
            return this.firstname + this.lastname
        },
        reverseWord: {
            get: function(){
                return this.word.split("").reverse().join("")
            },
            set: function(val){
                this.word = val.split("").reverse().join("")
            }
        },
        oddStudents: function(){
            let results = this.students.filter((student,index)=>{
                return student.age%2 == 0
            })
            return results
        }
    }
})

v-once

<div id="app">
    <!-- One time interpolation, no more modification -->
    <h1 v-once>{{ msg }}</h1>
</div>
var app = new Vue({
    el: "#app",
    data: {
        msg: "hello vue",
    }
})
app.msg = "hello front end"

The result is hello vue

v-html

<div id="app">
    <!-- insert HTML content -->
    <h1 v-html="htmlText"></h1>
</div>
var app = new Vue({
    el: "#app",
    data: {
        htmlText: "<span>hello</span>",
    }
})

hello

v-bind:id abbreviation: id

#login{
    color: red;
}
#register{
    color: aqua;
}
<div id="app">
    <!-- Modify attribute content -->
    <div :id="idname">
        <h1>Sign in</h1>
    </div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        idname: "login",
    }
})

Setting the value of idname is to set the value of id in div

For example, if you set idname: "login", the login color will look for #login attribute in CSS style, and then render the font as red. If you change it to "register", the font color will be changed to aqua

Expression application of template language

<div id="app">
    <!-- Expression application of template language -->
    <div>
        {{ firstname + lastname }}
    </div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        firstname: "Zhang",
        lastname: "three",
    }
})

Zhang San

watch (listener)

<div id="app">
    {{ msg }}
    <ul>
        <li v-for="item in arr">{{ item }}</li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        msg: "hello Vue",
        arr: ["Xiao Ming","Xiao Hong","Xiao Hei"]
    },
    watch: {
        // val is the modified value
        msg: function(val){
            console.log("Listening events------msg");
            console.log(val);
        },
        arr: function(val){
            console.log("Listening events------arr");
            console.log(val);
        }
    }
})

Modifying the value of the attribute in data will trigger the watch, for example

app.msg = "hello", watch will listen to msg

v-bind:class abbreviation: Class

.page {
    width: 200px;
    height: 200px;
    background: skyblue;
    display: none;
}
.active {
    display: block;
}
.col-xs-12 {
    display: block;
}
.red-bg {
    background: #FF0000;
}
.abc {
    display: block;
    background: yellow;
}
<div id="app">
    <!-- Determine whether a class exists by means of objects -->
    <div class="page" :class="{active:isTrue}"></div>
    <!-- Place objects directly -->
    <div class="page" :class="styleObj"></div>
    <!-- Place array -->
    <div class="page" :class="styleArr"></div>
    <!-- Place string -->
    <div class="page" :class="styleStr"></div>
    <!-- Mixed use of arrays and objects -->
    <div class="page" :class="styleArrObj"></div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        isTrue: false,
        // Place object
        styleObj: {
            "active": true,
            "laochen": true,
            "col-lg-6": true
        },
        // It can be added and deleted directly in the form of array
        styleArr: [
            "col-xs-12",
            "red-bg"
        ],
        // Place string
        styleStr: "page abc def",
        // Mixed use of arrays and objects
        styleArrObj: [
            "abcd",
            {
                active: true
            }
        ]
    }
})

v-bind:style abbreviation: Style

<div id="app">
    <div style="width: 100px;height: 100px;background: skyblue;"></div>
    <!-- CSS Inline style variable splicing -->
    <div style="width: 100px;height: 100px;background: skyblue;" :style="{ border: borderWidth+'px solid '+borderColor }"></div>
    <!-- CSS Inline style placement objects -->
    <div :style="styleObj"></div>
    <!-- CSS Array splicing -->
    <div :style="styleArr"></div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        borderWidth: 50,
        borderColor: "red",
        styleObj: {
            width: "200px",
            height: "300px",
            padding: "50px",
            "background-color": "skyblue"
        },
        styleArr: [
            {
                width: "200px",
                height: "300px",
                padding: "50px",
                "background-color": "skyblue"
            },
            {
                border: "30px solid yellow"
            }
        ]
    }
})

For example: CSS inline style variable splicing - the border of the second div will be set to the red border of 50px

v-model

You can use the v-model instruction to create two-way data binding on form < input > < textarea > and < Select > elements. It will automatically select the correct method to update the element according to the control type. Although some magic, v-model is essentially just a syntax sugar. It is responsible for monitoring user input events to update data, and some special processing for some extreme scenarios.

  • Single line text input box
<div id="app">
    <input type="" name="" v-model="username" value="" />
    <p>{{ username }}</p>
</div>
var app = new Vue({
    el: "#app",
    data: {
        username: "Zhang San"
    }
})

v-model binds the value and the value of the username variable together. When the value is modified, the value of the username variable will be automatically modified. This is the two-way binding of data

  • Multiline text input box
<textarea rows="" cols="" v-model="username"></textarea>
var app = new Vue({
    el: "#app",
    data: {
        username: "Zhang San"
    }
})
  • Check box: select the fruit you like
<span v-for="fruit in fruits">
    {{ fruit }}
    <input type="checkbox" name="fruit" id="" v-model="checkFruits" :value="fruit" />
</span>
<h2>{{ checkFruits }}</h2>
var app = new Vue({
    el: "#app",
    data: {
        fruits: ["Apple","Banana","snow pear","Grape"],
        checkFruits: []
    }
})

When selecting content, it will be added to the checkFruits array of v-model binding in turn

  • Radio box: choose your favorite fruit
<span v-for="fruit in fruits">
    {{ fruit }}
    <input type="radio" name="zfruit" id="" v-model="radioFruit" :value="fruit" />
</span>
<h2>{{ radioFruit }}</h2>
var app = new Vue({
    el: "#app",
    data: {
        fruits: ["Apple","Banana","snow pear","Grape"],
        radioFruit: ""
    }
})

When selecting content, it will add the last content you clicked to the radioFruit string

  • Option box: select the city you live in
<select v-model="chooseCity">
    <option disabled value="">Please select</option>
    <option v-for="city in citys" :value="city">{{ city }}</option>
</select>
<h3>{{ chooseCity }}</h3>
var app = new Vue({
    el: "#app",
    data: {
        citys: ["Beijing","Shanghai","Shenzhen","Guangzhou"],
        chooseCity: ""
    }
})

Bind the selected value with the null string of chooseCity to realize the two-way binding of data

  • Option box: select your favorite city

The multiple attribute enables multiple selections in the option box

<select v-model="moreCity" multiple="multiple">
    <option disabled value="">Please select</option>
    <option v-for="city in citys" :value="city">{{ city }}</option>
</select>
<h3>{{ moreCity }}</h3>
var app = new Vue({
    el: "#app",
    data: {
        citys: ["Beijing","Shanghai","Shenzhen","Guangzhou"],
        moreCity: []
    }
})

Hold down the CTRL key, select your favorite city, and bind the value of value and the value of moreCity array together to realize the two-way binding of data

  • Get string to number

.number

<input type="text" name="age" v-model.number="age" value="" />
var app = new Vue({
    el: "#app",
    data: {
        age: 16
    },
    watch: {
        // Listen for changes in the value of the age variable
        age: function(val){
            console.log(val);
        }
    }
})

add. After number, value can only be bound to age data Bi directionally when it is a number

  • lazy modifier

After the input text is finished, the value of the input box will be synchronized with the data to save performance

<input type="" name="" v-model.lazy="username" value="" />
var app = new Vue({
    el: "#app",
    data: {
        username: "Zhang San"
    }
})
  • trim modifier

Remove the spaces around the input

<input type="" name="" v-model.lazy.trim="username" value="" />
var app = new Vue({
    el: "#app",
    data: {
        username: "Zhang San"
    }
})

Tags: Vue

Posted by sp2hari on Sun, 15 May 2022 16:06:14 +0300