The title

Difference between V-show and V-if

  • V-if is false does not render the tag in the HTML tree
  • Render when v-show is false, the HTML tree has tags. But style = display: none

Why is key used in V-for

When Vue is updating a list of elements rendered using V-for, it defaults to the “update in place” policy. If the order of data items is changed, Vue will not move DOM elements to match the order of data items, but will update each element in place. To give Vue a hint that it can keep track of the identity of each node so that it can reuse and reorder existing elements, you need to provide a unique key for each item

knowledge

Instruction interpolation

Interpolation, expression

Instructions, dynamic properties

V-html: There is an XSS risk of overwriting subcomponents

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

        <hr/>
        <p v-html="rawHtml">
            <span>There are risks XSS</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-The ${Date.now()}`}}}</script>
Copy the code

The computed and watch

Computed is cached, and data does not recalculate if it remains unchanged

How does Watch monitor deeply?

Watch listens for the reference type and cannot get lodVal

<template>
    <div>
        <input v-model="name"/>
        <input v-model="info.city"/>
    </div>
</template>

<script>
export default {
    data() {
        return {
            name: The more 'double'.info: {
                city: 'Beijing'}}},watch: {
        name(newVal, oldVal) {
            // eslint-disable-next-line
            console.log('watch name', oldVal, newVal) // oldVal and val can be obtained normally
        },
        info: {
            handler(newVal, oldVal) {
                // eslint-disable-next-line
                console.log('watch info', oldVal, newVal) // Reference type, oldVal not available. Because the Pointers are the same, we're already pointing to a new val
            },
            deep: true // Deep monitor}}}</script>
</script>
Copy the code

Class and style

  • Using dynamic properties
  • I’ll write it in camel form
<template>
    <div>
        <p :class="{ black: isBlack, yellow: isYellow }">Use the class</p>
        <p :class="[black, yellow]">Using class (Array)</p>
        <p :style="styleData">Use the style</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isBlack: true.isYellow: true.black: 'black'.yellow: 'yellow'.styleData: {
                fontSize: '40px'.// Convert to hump
                color: 'red'.backgroundColor: '#ccc' // Convert to hump}}}}</script>

<style scoped>
    .black {
        background-color: # 999;
    }
    .yellow {
        color: yellow;
    }
</style>
Copy the code

Conditions apply colours to a drawing

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

Difference between V-if and V-show

  • V-if is false does not render the tag in the HTML tree
  • Render when v-show is false, the HTML tree has tags. But style = display: none

What are the use scenarios of V-if and V-show?

  • V-if is suitable for scenarios where the hidden display is not frequently switched
  • V-show is suitable for frequently switching to show hidden scenes
<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

Loop (list) rendering

  • How to variable objects? ———— can also use V-for
  • The importance of key. Key cannot be written arbitrarily (such as random or index)
  • V-for and V-if cannot be used together!
<template>
    <div>
        <p>Through the array</p>
        <ul>
            <li v-for="(item, index) in listArr" :key="item.id">
                {{index}} - {{item.id}} - {{item.title}}
            </li>
        </ul>

        <p>Traverse object</p>
        <ul >
            <li v-for="(val, key, index) in listObj" :key="key">
                {{index}} - {{key}} -  {{val.title}}
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            flag: false.listArr: [{id: 'a'.title: 'heading 1' }, // In the data structure, it is better to have id to facilitate the use of key
                { id: 'b'.title: 'title 2' },
                { id: 'c'.title: 'title'}].listObj: {
                a: { title: 'heading 1' },
                b: { title: 'title 2' },
                c: { title: 'title'},}}}}</script>
Copy the code

The event

Event parameter, custom parameter,

  • (If no parameter is passed, the event will be passed by default. If there is a custom parameter, use $event to pass the event.)

Event modifier

  • .stopStop the bubbling
  • .preventStop the default event
  • .captureInternal elements trigger limited handling in this tag
  • .selfOnly those triggered by themselves are processed
  • .onceOnly trigger once
  • .passiveThe default behavior of the scroll event is triggered immediately (this.passive modifier is especially useful on mobile)
<! -- Prevent the click event from propagating -->
<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
<! Events triggered by an inner element are processed here before they are processed by the inner element.
<div v-on:click.capture="doThis">.</div>

<! Trigger handler only if event.target is the current element itself -->
<! -- that is, events are not triggered from internal elements -->
<div v-on:click.self="doThat">.</div>
<! Click event will only trigger once -->
<a v-on:click.once="doThis"></a>
<! -- The default behavior of the scroll event (i.e. the scroll behavior) will be triggered immediately -->
<! Instead of waiting for 'onScroll' to finish -->
<! -- This includes' event.preventdefault () '-->
<div v-on:scroll.passive="onScroll">.</div>
Copy the code

Key modifier

When listening for keyboard events, we often need to check for detailed keystrokes. Vue allows v-ONS to add key modifiers when listening for keyboard events:

<! -- call 'vm.submit()' only if 'key' is' Enter '-->
<input v-on:keyup.enter="submit">
Copy the code

You can directly convert any valid keyname exposed by keyboardevent. key to kebab-case as a modifier.

<input v-on:keyup.page-down="onPageDown">
Copy the code

In the example above, the handler is only called when $Event. key equals PageDown.

System modifier

You can use the following modifier to implement a listener that fires a mouse or keyboard event only when the corresponding key is pressed.

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

Where is the event bound to?

  • An event is a native event object
  • The event is mounted to the current element, i.e., whatever element it is placed on
<template>
    <div>
        <p>{{num}}</p>
        <button @click="increment1">+ 1</button>
        <button @click="increment2(2, $event)">+ 2</button>
    </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) {
            // eslint-disable-next-line
            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

The form

  • V-model: Form input binding

Official documentation cn.vuejs.org/v2/guide/fo…

  • Common form item Textarea checkbox Radio select
  • The lazy number trim modifier

The lazy number trim modifier

  • .lazy– Update at “change” instead of “input”
  • .number– The input string is converted to a valid number
  • .trim– Enter the first and last Spaces for filtering

The official documentation

<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 selection (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: 'xx', age: 18, desc: 'self-introduction ', checked: true, checkedNames: [], gender: 'male', selected: '', selectedList: [] } } } </script>Copy the code