search
HomeWeb Front-endVue.jsLearn more about debugging tools and directives in Vue

This article will take you to continue learningVue, and introduce in detail the debugging tools and instructions that are essential knowledge for getting started with Vue. I hope it will be helpful to everyone!

Learn more about debugging tools and directives in Vue

vue debugging tool


(1) Install vue-devtools debugging tool

vue The vue-devtools debugging tool officially provided by vue can facilitate developers to debug and develop vue projects. (Learning video sharing: vue video tutorial)

1️⃣ Chrome browser online installation vue-devtools:

  • vue 2.x Debugging tools:
    https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd
  • vue 3.x debugging tools:
    https://chrome.google.com/webstore/detail/vuejs-devtools/ljjemllljcmogpfapbkkighbhhppjdbg
##2️⃣

If you cannot install it online using the Chrome browser, I will do the following Two resource packages are given, click on the address to download immediately!! !

    vue 2.x debugging tool:

  • https:// download.csdn.net/download/battledao/85047060
  • vue 3.x debugging tool:

  • https://download.csdn.net/download/battledao/85047073
?Warm reminder?: The browser debugging tools of vue2 and vue3 cannot be used cross-wise!

(2) Configure vue-devtools in the Chrome browser

Click the three-dot button in the upper right corner of the Chrome browser and select More Tools → Extensions → Vue.js devtools detailed information, and check the following two options:

Learn more about debugging tools and directives in Vue

(3) Use vue-devtools to debug the vue page

Visit a page using vue in the browser, open the browser's developer tools, switch to the Vue panel, and use

vue-devtools to debug the current page.

Learn more about debugging tools and directives in Vue

4. Vue instructions


(1) Concept of instructions

1️⃣

Directives is the template syntax provided by vue for developers, which is used to assist developers in rendering the basic structure of the page.

2️⃣ The instructions in vue

can be divided into the following 6 categories according to different uses:

    Content rendering
  • Instructions
  • Attribute binding
  • Instruction
  • Event binding
  • Instruction
  • Two-way binding
  • Instruction
  • Conditional rendering
  • Instructions
  • List rendering
  • Instructions
  • ?Warm reminder?: Instructions are the most basic and commonly used in vue development. The simplest knowledge point.

(2) Content rendering instructions

Content rendering instructions

are used to assist developersrender the text content of DOM elements . There are three commonly used content rendering instructions:

v-text
  • {
  • { }}
  • v-html
2.1 v-text

The code demonstration is as follows:


Learn more about debugging tools and directives in Vue?Warm reminder?:

v-text

command Will overwrite the default value within the element.

2.2 {

{ }} Syntax

{

{ }} Syntax provided by vue , specifically used to solve the problem that v-text will overwrite the default text content. The professional name of this <!-- -->{{ }} syntax is <!-- -->interpolation expression (English name: Mustache). The code demonstration is as follows:


?Warm reminder?: Compared with the Learn more about debugging tools and directives in Vuev-text
instruction, interpolation expressions are more commonly used in development Some! Because it does not overwrite the default text content in the element.

2.3 v-html

v-text directives and interpolation expressions can only render plain text content. If you want to

render a string containing HTML tags into the HTML element

of the page, you need to use the v-html directive. The code demonstration is as follows:

<!-- 假设data 中定义了名为 desc 的数据,数据的值为包含 HTML 标签的字符串 -->
<!-- info: &#39;<h4 id="欢迎大家来学习-nbsp-vue-js">欢迎大家来学习 vue.js</h4>&#39; -->
<p v-html="info"></p>

2.4 Content rendering instructions - complete code demonstration

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <p v-text="username"></p>
        <p v-text="gender">性别:</p>

        <hr>

        <p>姓名:{{ username }}</p>
        <p>性别:{{ gender }}</p>

        <hr>

        <div v-text="info"></div>
        <div>{{ info }}</div>
        <div v-html="info"></div>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                username: &#39;battledao&#39;,
                gender: &#39;男&#39;,
                info: &#39;<h4 id="欢迎大家来学习-nbsp-vue-js">欢迎大家来学习 vue.js</h4>&#39;
            }
        })
    </script>
</body>

</html>

(3) Attribute binding instructions

If necessary dynamically bind the attributes of the element If the attribute value is , you need to use the v-bind attribute binding instruction. Usage examples are as follows:

Learn more about debugging tools and directives in Vue

##3.1 Short form of attribute binding directive

Due to

v-bind directive It is used very frequently in development, so Vue officially provides it with the abbreviation form (abbreviation is : in English).

Learn more about debugging tools and directives in Vue

3.2 Using Javascript expressions

In the template rendering syntax provided by vue, in addition to supporting

binding simple In addition to data values ​​

, it also supports the operation of Javascript expressions , for example:

Learn more about debugging tools and directives in Vue

3.3 Attribute binding instructions - complete code Demonstration

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <input type="text" :placeholder="tips">
        <hr>
        <!-- vue 规定 v-bind: 指令可以简写为 : -->
        <img src="/static/imghwm/default1.png"  data-src="photo"  class="lazy"  : alt=""   style="max-width:90%">

        <hr>
        <div>1 + 2 的结果是:{{ 1 + 2 }}</div>
        <div>{{ tips }} 反转的结果是:{{ tips.split(&#39;&#39;).reverse().join(&#39;&#39;) }}</div>
        <div :title="&#39;box&#39; + index">这是一个 div</div>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                tips: &#39;请输入用户名&#39;,
                photo: &#39;https://cn.vuejs.org/images/logo.svg&#39;,
                index: 3
            }
        })
    </script>
</body>

</html>

(4) Event binding instructions

1️⃣ vue provides

v-on

event binding instructions for Assist programmers to bind event listeners to DOM elements. The syntax format is as follows:

Learn more about debugging tools and directives in Vue?Warm reminder?: The native DOM object has native events such as onclick, oninput, and onkeyup. After replacing them with vue's event binding form, they are: v-on:click, v-on:input, v-on:keyup

2️⃣ The event processing function bound by

v-on

needs to be in the methods node Statement :

Learn more about debugging tools and directives in Vue

4.1 Shorthand for event binding

due to the

v-on

directive It is used frequently in development, so Vue officially provides the abbreviation form (abbreviated as @ in English).

Learn more about debugging tools and directives in Vue

4.2 Event parameter object

In native DOM event binding, you can use the formal parameter of the event processing function, Receive event parameter object event. Similarly, in the event processing function bound to the

v-on

instruction (abbreviated as @), can also receive the event parameter object event, example The code is as follows:

Learn more about debugging tools and directives in Vue##4.3 Bind events and pass parameters

Use the v-on

command to bind When specifying an event, you can use

( ) to pass parameters. The sample code is as follows:

Learn more about debugging tools and directives in Vue4.4 Event Binding Instructions - Complete Code Demonstration

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <p>count 的值是:{{ count }}</p>
        <!-- 在绑定事件处理函数的时候,可以使用 () 传递参数 -->
        <!-- v-on: 指令可以被简写为 @ -->
        <button @click="add(1)">+1</button>
        <button @click="sub">-1</button>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                count: 0
            },
            // methods 的作用,就是定义事件的处理函数
            methods: {
                add(n) {
                    // 在 methods 处理函数中,this 就是 new 出来的 vm 实例对象
                    // console.log(vm === this)
                    console.log(vm)
                    // vm.count += 1
                    this.count += n
                },
                sub() {
                    // console.log(&#39;触发了 sub 处理函数&#39;)
                    this.count -= 1
                }
            }
        })
    </script>
</body>

</html>
4.5 $event

$event

is a special variable provided by vue, used to represent the native event parameter object event.

$event can solve the problem of event parameter object event being overwritten. Example usage is as follows: The complete code demonstration is as follows:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <p>count 的值是:{{ count }}</p>
        <!-- 如果 count 是偶数,则 按钮背景变成红色,否则,取消背景颜色 -->
        <!-- <button @click="add">+N</button> -->
        <!-- vue 提供了内置变量,名字叫做 $event,它就是原生 DOM 的事件对象 e -->
        <button @click="add($event, 1)">+N</button>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                count: 0
            },
            methods: {
                add(e, n) {
                    this.count += n
                    console.log(e)

                    // 判断 this.count 的值是否为偶数
                    if (this.count % 2 === 0) {
                        // 偶数
                        e.target.style.backgroundColor = &#39;red&#39;
                    } else {
                        // 奇数
                        e.target.style.backgroundColor = &#39;&#39;
                    }
                }
            },
        })
    </script>
</body>

</html>

4.6 Event modifier

Call event.preventDefault in the event processing function ()

or

event.stopPropagation() are very common requirements. Therefore, vue provides the concept of event modifiers to assist programmers to more conveniently control the triggering of events. The five commonly used event modifiers are as follows:

##Event modifierDescription.prevent.stop in capture mode Trigger the current event processing functionThe bound event is only triggered onceThe event handler is only triggered when event.target is the current element itself
Prevent the default behavior (for example: prevent the jump of a connection, prevent the submission of the form, etc.)
Stop event bubbling .capture
.once
.self

完整代码演示如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <a href="http://www.baidu.com" @click.prevent="show">跳转到百度首页</a>

        <hr>

        <div style="height: 150px; background-color: pink; padding-left: 100px; line-height: 150px;"
        @click="divHandler">
            <button @click.stop="btnHandler">按钮</button>
        </div>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {},
            methods: {
                show() {
                    console.log(&#39;点击了 a 链接&#39;)
                },
                btnHandler() {
                    console.log(&#39;btnHandler&#39;)
                },
                divHandler() {
                    console.log(&#39;divHandler&#39;)
                }
            },
        })
    </script>
</body>

</html>

4.7 按键修饰符

在监听键盘事件时,我们经常需要判断详细的按键。此时,可以为键盘相关的事件添加按键修饰符

完整代码演示如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <input type="text" @keyup.esc="clearInput" @keyup.enter="commitAjax">
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {},
            methods: {
                clearInput(e) {
                    console.log(&#39;触发了 clearInput 方法&#39;)
                    e.target.value = &#39;&#39;
                },
                commitAjax() {
                    console.log(&#39;触发了 commitAjax 方法&#39;)
                }
            },
        })
    </script>
</body>

</html>

(5)双向绑定指令

vue 提供了 v-model 双向数据绑定指令,用来辅助开发者在不操作 DOM 的前提下,快速获取表单的数据

完整代码演示如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
    <div id="app">
        <p>用户的名字是:{{ username }}</p>
        <input type="text" v-model="username">
        <hr>
        <input type="text" :value="username">
        <hr>
        <select v-model="city">
            <option value="">请选择城市</option>
            <option value="1">北京</option>
            <option value="2">上海</option>
            <option value="3">广州</option>
        </select>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                username: &#39;battledao&#39;,
                city: &#39;2&#39;
            }
        })
    </script>
</body>

</html>

5.1 v-model 指令的修饰符

为了方便对用户输入的内容进行处理,vue 为 v-model 指令提供了 3 个修饰符,分别是:

修饰符 作用 示例
.number 自动将用户的输入值转为数值类型
.trim 自动过滤用户输入的首尾空白字符
.lazy 在“change”时而非“input”时更新

完整代码演示如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们把数据填充到 div 内部 -->
    <div id="app">
        <input type="text" v-model.number="n1"> + <input type="text" v-model.number="n2"> = <span>{{ n1 + n2 }}</span>
        <hr>
        <input type="text" v-model.trim="username">
        <button @click="showName">获取用户名</button>
        <hr>
        <input type="text" v-model.lazy="username">
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                username: &#39;battledao&#39;,
                n1: 1,
                n2: 2
            },
            methods: {
                showName() {
                    console.log(`用户名是:"${this.username}"`)
                }
            },
        })
    </script>
</body>

</html>

(6)条件渲染指令

条件渲染指令用来辅助开发者按需控制 DOM 的显示与隐藏。条件渲染指令有如下两个,分别是:

  • v-if
  • v-show

代码演示如下:

Learn more about debugging tools and directives in Vue

6.1 v-if 和 v-show 的区别(面试常问)

实现原理不同:

  • v-if 指令会动态地创建或移除DOM 元素,从而控制元素在页面上的显示与隐藏;
  • v-show 指令会动态为元素添加或移除 style=“display: none;” 样式,从而控制元素的显示与隐藏;

性能消耗不同:v-if 有更高的切换开销,而 v-show 有更高的初始渲染开销。因此:

  • 如果需要非常频繁地切换,则使用 v-show 较好;
  • 如果在运行时条件很少改变,则使用 v-if 较好;

6.2 v-else

v-if 可以单独使用,或配合 v-else 指令一起使用:
Learn more about debugging tools and directives in Vue

?温馨提醒?:v-else 指令必须配合 v-if 指令一起使用,否则它将不会被识别!

6.3 v-else-if

v-else-if 指令,顾名思义,充当 v-if 的“else-if 块”,可以连续使用:
Learn more about debugging tools and directives in Vue

?温馨提醒?:v-else-if 指令必须配合 v-if 指令一起使用,否则它将不会被识别!

6.4 条件渲染指令 - 完整代码演示

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们把数据填充到 div 内部 -->
    <div id="app">
        <p v-if="flag">这是被 v-if 控制的元素</p>
        <p v-show="flag">这是被 v-show 控制的元素</p>

        <hr>
        <div v-if="type === &#39;A&#39;">优秀</div>
        <div v-else-if="type === &#39;B&#39;">良好</div>
        <div v-else-if="type === &#39;C&#39;">一般</div>
        <div v-else>差</div>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                // 如果 flag 为 true,则显示被控制的元素;如果为 false 则隐藏被控制的元素
                flag: false,
                type: &#39;A&#39;
            }
        })
    </script>
</body>

</html>

(7)列表渲染指令

vue 提供了 v-for 列表渲染指令,用来辅助开发者基于一个数组来循环渲染一个列表结构。v-for 指令需要使用 item in items 形式的特殊语法,其中:

  • items 是待循环的数组
  • item 是被循环的每一项

代码演示如下:

Learn more about debugging tools and directives in Vue

7.1 v-for 中的索引

v-for 指令还支持一个可选的第二个参数,即当前项的索引。语法格式为 (item, index) in items,示例代码如下:
Learn more about debugging tools and directives in Vue

?温馨提醒?:v-for 指令中的 item 项index 索引都是形参,可以根据需要进行重命名。例如 (user, i) in userlist

7.2 列表渲染指令 - 完整代码演示

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./lib/bootstrap.css">
</head>

<body>
    <!-- 希望 Vue 能够控制下面的这个 div,帮我们把数据填充到 div 内部 -->
    <div id="app">
        <table class="table table-bordered table-hover table-striped">
            <thead>
                <th>索引</th>
                <th>Id</th>
                <th>姓名</th>
            </thead>
            <tbody>
                <!-- 官方建议:只要用到了 v-for 指令,那么一定要绑定一个 :key 属性 -->
                <!-- 而且,尽量把 id 作为 key 的值 -->
                <!-- 官方对 key 的值类型,是有要求的:字符串或数字类型 -->
                <!-- key 的值是千万不能重复的,否则会终端报错:Duplicate keys detected -->
                <tr v-for="(item, index) in list" :key="item.id">
                    <td>{{ index }}</td>
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
    <script src="./lib/vue-2.6.12.js"></script>
    <!-- 2. 创建 Vue 的实例对象 -->
    <script>
        // 创建 Vue 的实例对象
        const vm = new Vue({
            // el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
            el: &#39;#app&#39;,
            // data 对象就是要渲染到页面上的数据
            data: {
                list: [
                    { id: 1, name: &#39;张三&#39; },
                    { id: 2, name: &#39;李四&#39; },
                    { id: 3, name: &#39;王五&#39; },
                    { id: 4, name: &#39;张三&#39; },
                ]
            }
        })
    </script>
</body>

</html>

7.3 使用 key 维护列表的状态

1️⃣ 当列表的数据变化时,默认情况下,vue 会尽可能的复用已存在的DOM 元素,从而提升渲染的性能。但这种默认的性能优化策略,会导致有状态的列表无法被正确更新

2️⃣ 为了给 vue 一个提示,以便它能跟踪每个节点的身份,从而在保证有状态的列表被正确更新的前提下,提升渲染的性能。此时,需要为每项提供一个唯一的 key 属性

Learn more about debugging tools and directives in Vue

完整代码演示如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 在页面中声明一个将要被 vue 所控制的 DOM 区域 -->
    <div id="app">

        <!-- 添加用户的区域 -->
        <div>
            <input type="text" v-model="name">
            <button @click="addNewUser">添加</button>
        </div>

        <!-- 用户列表区域 -->
        <ul>
            <li v-for="(user, index) in userlist" :key="user.id">
                <input type="checkbox" />
                姓名:{{user.name}}
            </li>
        </ul>
    </div>

    <script src="./lib/vue-2.6.12.js"></script>
    <script>
        const vm = new Vue({
            el: &#39;#app&#39;,
            data: {
                // 用户列表
                userlist: [
                    { id: 1, name: &#39;zs&#39; },
                    { id: 2, name: &#39;ls&#39; }
                ],
                // 输入的用户名
                name: &#39;&#39;,
                // 下一个可用的 id 值
                nextId: 3
            },
            methods: {
                // 点击了添加按钮
                addNewUser() {
                    this.userlist.unshift({ id: this.nextId, name: this.name })
                    this.name = &#39;&#39;
                    this.nextId++
                }
            },
        })
    </script>
</body>

</html>

7.4 key 的注意事项

  • key 的值只能是字符串数字类型

  • key 的值必须具有唯一性(即:key 的值不能重复)

  • 建议把数据项 id 属性的值作为 key 的值(因为 id 属性的值具有唯一性)

  • 使用 index 的值当作 key 的值没有任何意义(因为index 的值不具有唯一性)

  • It is recommended that when using the v-for instructionBe sure to specify the value of key (both to improve performance and prevent list status disorder)

(Learning video sharing: web front-end development, Basic programming video)

The above is the detailed content of Learn more about debugging tools and directives in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software