vue2 Common instructions in vue

1. Why should you learn Vue?

1. Essential front-end skills

2. There are many jobs, and most Internet companies are using Vue.

3. Improve development efficiency

4. Essential skills for high salary (Vue2+Vue3)

2. What is Vue

Concept: Vue (pronounced /vjuː/, similar to view) is a progressive framework for building user interfaces

Vue2 official website: https://v2.cn.vuejs.org/

1. What is building a user interface?

Render an interface that users can see based on data

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-sV4imehW-1692880626761)(assets/1681875887026.png)]

2. What is progressive

The so-called progressive approach means step by step. You don’t have to learn all the APIs in Vue to develop Vue. You can learn a little and develop a little.

Two development methods of Vue:

1. Vue核心包开发

Scenario: Local module transformation

2. Vue核心包&Vue插件&工程化

Scenario: Whole site development

3. What is a framework

The so-called framework: it is a complete set of solutions

Give a chestnut

If a complete project is compared to a renovated house, then the framework is a rough house.

We only need to add functional codes on the basis of the "rough house".

When it comes to frameworks, we have to mention libraries.

  • A library, similar to a toolbox, is a collection of methods, such as axios, lodash, echarts, etc.
  • The framework is a complete solution that implements most of the functions. We only need to code according to certain rules.

The picture below is a comparison of libraries and frameworks.

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-bwNHTZWh-1692880626763)(assets/1681876620277.png)]

Characteristics of a framework: It has a set of rules or constraints that developers must abide by.

3. Create a Vue instance

We already know that the Vue framework can help us render the user interface based on data, so what should we do?

Core steps (4 steps):

  1. Prepare container
  2. Yinbao (official website) — development version/production version
  3. Create a Vue instance new Vue()
  4. Specify configuration items and render data
    1. el:Specify the mount point
    2. data provides data

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-r4tcxTxB-1692880626764)(assets/1681877405007.png)]

4. Interpolation expression { {}}

Interpolation expression is a template syntax of Vue. We can use interpolation expression to render the data provided by Vue.

1. Function: Use expressions to interpolate and render them into the page.

Expression: It is a code that can be evaluated, and the JS engine will calculate a result

The following situations are all expressions:

money + 100
money - 100
money * 10
money / 10 
price >= 100 ? '真贵':'还行'
obj.name
arr[0]
fn()
obj.fn()

2. Grammar

Interpolation expression syntax: { {expression}}

<h3>{
    
    {
    
    title}}<h3>

<p>{
    
    {
    
    nickName.toUpperCase()}}</p>

<p>{
    
    {
    
    age >= 18 ? '成年':'未成年'}}</p>

<p>{
    
    {
    
    obj.name}}</p>

<p>{
    
    {
    
    fn()}}</p>

3. Wrong usage

1.在插值表达式中使用的数据 必须在data中进行了提供
<p>{
    
    {
    
    hobby}}</p>  //如果在data中不存在 则会报错

2.支持的是表达式,而非语句,比如:if   for ...
<p>{
    
    {
    
    if}}</p>

3.不能在标签属性中使用 {
    
    {
    
      }} 插值 (插值表达式只能标签中间使用)
<p title="{
    
    {username}}">我是P标签</p>

5. Responsive features

1. What is responsiveness?

​ A simple understanding is that the data changes and the view changes accordingly.

2. How to access and modify data in data (responsive demonstration)

The data in data will eventually be added to the instance

① Access data: "Instance.Attribute name"

② Modify data: "Instance.Attribute name" = "Value"

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-paalOxcf-1692880626766)(assets/1681888539340.png)]

6. Installation of Vue developer tools

  1. Install through Google Play Store (foreign website)
  2. Minimalist plug-in download (recommended) https://chrome.zzzmh.cn/index

installation steps:

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-XJNpm84z-1692880626767)(assets/1681889390406.png)]

After installation, you can see an additional Vue debugging panel after F12.

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-m47NoySH-1692880626767)(assets/1681889483446.png)]

7. Common instructions in Vue

Concept: Directives are special tag attributes provided by Vue with v- prefix .

Why you should learn it: To improve programmers’ efficiency in operating DOM.

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

  • Content rendering instructions (v-html, v-text)
  • Conditional rendering instructions (v-show, v-if, v-else, v-else-if)
  • Event binding instructions (v-on)
  • Attribute binding directive (v-bind)
  • Two-way binding instructions (v-model)
  • List rendering instructions (v-for)

Instructions are the most basic, commonly used, and simplest knowledge points in Vue development.

8. Content rendering instructions

Content rendering instructions are used to assist developers in rendering the text content of DOM elements. There are two commonly used content rendering instructions:

  • v-text (similar to innerText)

    • Usage syntax: <p v-text="uname">hello</p>, which means to render the uame value into the p tag
    • Similar to innerText, using this syntax will overwrite the original content of the p tag.
  • v-html (similar to innerHTML)

    • Use syntax: <p v-html="intro">hello</p>, which means rendering the intro value into the p tag
    • Similar to innerHTML, using this syntax will overwrite the original content of the p tag.
    • Similar to innerHTML, using this syntax, the style of HTML tags can be presented.

Code demo:

 
  <div id="app">
    <h2>个人信息</h2>
	// 既然指令是vue提供的特殊的html属性,所以咱们写的时候就当成属性来用即可
    <p v-text="uname">姓名:</p> 
    <p v-html="intro">简介:</p>
  </div> 

<script>
        const app = new Vue({
    
    
            el:'#app',
            data:{
    
    
                uname:'张三',
                intro:'<h2>这是一个<strong>非常优秀</strong>的boy<h2>'
            }
        })
</script>

9. Conditional rendering instructions

Conditional judgment instructions are used to assist developers in controlling the display and hiding of DOM as needed. There are two conditional rendering instructions, namely:

  1. v-show

    1. Function: Control the display and hiding of elements
    2. Syntax: v-show = "expression" The expression value is true to display, false to hide
    3. Principle: Switch display:none to control display and hiding
    4. Scene: frequently switch to show hidden scenes

    [The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-wZtWkxkf-1692880626768)(assets/1681891228284.png)]

  2. v-if

    1. Function: Control the display and hiding of elements (conditional rendering)
    2. Syntax: v-if= “expression” The expression value true is displayed, false is hidden
    3. Principle: Based on conditional judgment, whether to create or remove element nodes
    4. Scene: Either show or hide, scenes that are not frequently switched

    [The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-czuWaJ9P-1692880626769)(assets/1681891237750.png)]

    Sample code:

      <body>
     
       <!-- 
         v-show底层原理:切换 css 的 display: none 来控制显示隐藏
         v-if  底层原理:根据 判断条件 控制元素的 创建 和 移除(条件渲染)
       -->
     
       <div id="app">
         <div v-show="flag" class="box">我是v-show控制的盒子</div>
         <div v-if="flag" class="box">我是v-if控制的盒子</div>
       </div>
       
       <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
       <script>
         const app = new Vue({
            
            
           el: '#app',
           data: {
            
            
             flag: false
           }
         })
       </script>
     
     </body>
    
  3. v-else 和 v-else-if

    1. Function: Assist v-if to judge rendering
    2. Syntax: v-else v-else-if="expression"
    3. Need to be used immediately after v-if

Sample code:

<!DOCTYPE html>
<html lang="en">
<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>
 
 <div id="app">
   <p v-if="gender === 1">性别:♂ 男</p>
   <p v-else>性别:♀ 女</p>
   <hr>
   <p v-if="score >= 90">成绩评定A:奖励电脑一台</p>
   <p v-else-if="score >= 70">成绩评定B:奖励周末郊游</p>
   <p v-else-if="score >= 60">成绩评定C:奖励零食礼包</p>
   <p v-else>成绩评定D:惩罚一周不能玩手机</p>
 </div>
 
 <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
 <script>

   const app = new Vue({
      
      
     el: '#app',
     data: {
      
      
       gender: 2,
       score: 95
     }
   })
 </script>

</body>
</html>

10. Event binding instructions

When using Vue, if you need to register events for the DOM, it is extremely simple. The syntax is as follows:

  • <button v-on: event name="inline statement"> button
  • <button v-on: event name="handler function">Button
  • <button v-on: event name="Handling function (actual parameters)">Button
  • v-on:Abbreviated as @
  1. inline statement

    <div id="app">
        <button @click="count--">-</button>
        <span>{
          
          {
          
           count }}</span>
        <button v-on:click="count++">+</button>
      </div>
      <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
      <script>
        const app = new Vue({
          
          
          el: '#app',
          data: {
          
          
            count: 100
          }
        })
      </script>
    
  2. event handler

    Notice:

    • The event handling function should be written in a configuration item (methods) at the same level as data
    • This inside the functions in methods all points to the Vue instance
<body>
  <div id="app">
    <button @click="fn">切换显示隐藏</button>
    <h1 v-show="isShow">学习vue</h1>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app4 = new Vue({
      
      
      el: '#app',
      data: {
      
      
        isShow: true
      },
      methods: {
      
      
        fn () {
      
      
          // 让提供的所有methods中的函数,this都指向当前实例
          // console.log('执行了fn', app.isShow)
          // console.log(app3 === this)
          this.isShow = !this.isShow
        }
      }
    })
  </script>
</body>

3. Pass parameters to the event processing function

  • If no parameters are passed, the method does not need parentheses; e can be used directly as the event object in the methods method.

  • If parameters are passed, the actual parameters $eventrepresent the event object, fixed usage.

 <body>

  <div id="app">
    <div class="box">
      <h3>小黑自动售货机</h3>
      <button @click="buy(5)">可乐5元</button>
      <button @click="buy(10)">咖啡10元</button>
      <button @click="buy(8)">牛奶8元</button>
    </div>
    <p>银行卡余额:{
   
   { money }}元</p>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      
      
      el: '#app',
      data: {
      
      
        money: 100
      },
      methods: {
      
      
        buy (price) {
      
      
          this.money -= price
        }
      }
    })
  </script>
</body>

11. Attribute binding instructions

  1. Function : Dynamically set HTML tag attributes such as: src, url, title
  2. Syntax : **v-bind:**Attribute name="expression"
  3. v-bind : can be abbreviated as :

For example, there is a picture, and its srcattribute value is an image address. This address is stored in data data.

Then you can set the attribute value like this:

  • <img v-bind:src="url" />
  • <img :src="url" />(v-bind can be omitted)
  <div id="app">
    <img v-bind:src="imgUrl" v-bind:title="msg" alt="">
    <img :src="imgUrl" :title="msg" alt="">
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
    
    
      el: '#app',
      data: {
    
    
        imgUrl: './imgs/10-02.png',
        msg: 'hello 波仔'
      }
    })
  </script>

12. Small case - Bo Zai’s learning journey

Requirements: The first picture in the array is displayed by default. Click on the previous page and next page to switch back and forth between the pictures in the array.

Implementation ideas:

1. Array storage image path ['url1', 'url2', 'url3',...]

2. You can prepare a subscript index to get the image address from the array.

3. Bind the current image address to src through v-bind

4. Click on the previous page and next page and you only need to modify the subscript value.

5. When showing the first picture, the previous page button should be hidden. When showing the last picture, the next page button should be hidden

<!DOCTYPE html>
<html lang="en">
<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>
  <div id="app">
    <button v-show="index > 0" @click="index--">上一页</button>
    <div>
      <img :src="list[index]" alt="">
    </div>
    <button v-show="index < list.length - 1" @click="index++">下一页</button>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      
      
      el: '#app',
      data: {
      
      
        index: 0,
        list: [
          './imgs/11-00.gif',
          './imgs/11-01.gif',
          './imgs/11-02.gif',
          './imgs/11-03.gif',
          './imgs/11-04.png',
          './imgs/11-05.png',
        ]
      }
    })
  </script>
</body>
</html>

13. List rendering instructions

Vue provides the v-for list rendering instruction to assist developers in looping and rendering a list structure based on an array.

The v-for directive requires (item, index) in arrspecial syntax of the form , where:

  • item is each item in the array
  • index is the index of each item and can be omitted if not needed
  • arr is the array being traversed

This syntax can also iterate over objects and numbers

//遍历对象
<div v-for="(value, key, index) in object">{
    
    {
    
    value}}</div>
value:对象中的值
key:对象中的键
index:遍历索引从0开始

//遍历数字
<p v-for="item in 10">{
    
    {
    
    item}}</p>
item从1 开始

14. Small case-Xiao Hei’s bookshelf

need:

1. Render the right list based on the data on the left (v-for)

2. When clicking the delete button, the current row should be deleted from the list (get the ID of the current row and use filter to filter)

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-6c3eGNGC-1692880626770)(assets/1681896632672.png)]

Prepare the code:

<!DOCTYPE html>
<html lang="en">
<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>

  <div id="app">
    <h3>小黑的书架</h3>
    <ul>
      <li v-for="(item, index) in booksList" :key="item.id">
        <span>{
   
   { item.name }}</span>
        <span>{
   
   { item.author }}</span>
        <!-- 注册点击事件 →  通过 id 进行删除数组中的 对应项 -->
        <button @click="del(item.id)">删除</button>
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      
      
      el: '#app',
      data: {
      
      
        booksList: [
          {
      
       id: 1, name: '《红楼梦》', author: '曹雪芹' },
          {
      
       id: 2, name: '《西游记》', author: '吴承恩' },
          {
      
       id: 3, name: '《水浒传》', author: '施耐庵' },
          {
      
       id: 4, name: '《三国演义》', author: '罗贯中' }
        ]
      },
      methods: {
      
      
        del (id) {
      
      
          // console.log('删除', id)
          // 通过 id 进行删除数组中的 对应项 → filter(不会改变原数组)
          // filter: 根据条件,保留满足条件的对应项,得到一个新数组。
          // console.log(this.booksList.filter(item => item.id !== id))
          this.booksList = this.booksList.filter(item => item.id !== id)
        }
      }
    })
  </script>
</body>
</html>

15. Key in v-for

Syntax: key="unique value"

Function: Add a unique identifier to the list item . It is convenient for Vue to correctly sort and reuse list items.

Why add key : Vue’s default behavior will try to modify elements in place ( reuse in place )

Example code:

<ul>
  <li v-for="(item, index) in booksList" :key="item.id">
    <span>{
    
    {
    
     item.name }}</span>
    <span>{
    
    {
    
     item.author }}</span>
    <button @click="del(item.id)">删除</button>
  </li>
</ul>

Notice:

  1. The value of key can only be string or numeric type
  2. The value of key must be unique
  3. It is recommended to use id as the key (unique), and it is not recommended to use index as the key (it will change and does not correspond)

16. Two-way binding instructions

The so-called two-way binding is:

  1. After the data changes, the rendered page results will be updated.
  2. After the page results are updated, the data will also change accordingly.

Function: used for form elements (input, radio, select), two-way binding data, can quickly obtain or set the content of form elements

Syntax : v-model="variable"

Requirements : Use two-way binding to achieve the following requirements

  1. Click the login button to get the content in the form
  2. Click the reset button to clear the contents of the form

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-KMIZkESW-1692880626772)(assets/1681913125738.png)]

<!DOCTYPE html>
<html lang="en">

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

  <div id="app">
    <!-- 
      v-model 可以让数据和视图,形成双向数据绑定
      (1) 数据变化,视图自动更新
      (2) 视图变化,数据自动更新
      可以快速[获取]或[设置]表单元素的内容
     -->
    账户:<input type="text" v-model="username"> <br><br>
    密码:<input type="password" v-model="password"> <br><br>
    <button @click="login">登录</button>
    <button @click="reset">重置</button>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      
      
      el: '#app',
      data: {
      
      
        username: '',
        password: ''
      },
      methods: {
      
      
        login() {
      
      
          console.log(this.username, this.password)
        },
        reset() {
      
      
          this.username = ''
          this.password = ''
        }
      }
    })
  </script>
</body>

</html>

17. Comprehensive Case-Xiaohei Notepad

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-aOSJwCXh-1692880626772)(assets/1681914565816.png)]

Functional Requirements:

  1. List rendering

  2. Delete function

  3. Add functionality

  4. Bottom statistics and clearing

<!DOCTYPE html>
<html lang="en">
<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" />
<link rel="stylesheet" href="./css/index.css" />
<title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
  <!-- 输入框 -->
  <header class="header">
    <h1>小黑记事本</h1>
    <input v-model="todoName"  placeholder="请输入任务" class="new-todo" />
    <button @click="add" class="add">添加任务</button>
  </header>
  <!-- 列表区域 -->
  <section class="main">
    <ul class="todo-list">
      <li class="todo" v-for="(item, index) in list" :key="item.id">
        <div class="view">
          <span class="index">{
   
   { index + 1 }}.</span> <label>{
   
   { item.name }}</label>
          <button @click="del(item.id)" class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
  <!-- 统计和清空 → 如果没有任务了,底部隐藏掉 → v-show -->
  <footer class="footer" v-show="list.length > 0">
    <!-- 统计 -->
    <span class="todo-count">合 计:<strong> {
   
   { list.length }} </strong></span>
    <!-- 清空 -->
    <button @click="clear" class="clear-completed">
      清空任务
    </button>
  </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  // 添加功能
  // 1. 通过 v-model 绑定 输入框 → 实时获取表单元素的内容
  // 2. 点击按钮,进行新增,往数组最前面加 unshift
  const app = new Vue({
      
      
    el: '#app',
    data: {
      
      
      todoName: '',
      list: [
        {
      
       id: 1, name: '跑步一公里' },
        {
      
       id: 2, name: '跳绳200个' },
        {
      
       id: 3, name: '游泳100米' },
      ]
    },
    methods: {
      
      
      del (id) {
      
      
        // console.log(id) => filter 保留所有不等于该 id 的项
        this.list = this.list.filter(item => item.id !== id)
      },
      add () {
      
      
        if (this.todoName.trim() === '') {
      
      
          alert('请输入任务名称')
          return
        }
        this.list.unshift({
      
      
          id: +new Date(),
          name: this.todoName
        })
        this.todoName = ''
      },
      clear () {
      
      
        this.list = []
      }
    }
  })

</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_46370595/article/details/132482189