Vue - interpolation operation, dynamic binding properties

Table of contents

1. Interpolation operation

1.Mustache syntax

2. Display of vue list (v-for)

3. Vue case-counter

4. Common command v-once

5. Common command v-html

6. Common command v-text 

7. Common command v-pre

8. Common command v-cloak

Two, dynamic binding properties

1. v-bind instruction

2. v-bind dynamic binding class (object syntax)

3. Combination of v-bind and v-for

4 v-bind dynamic binding class (array usage)

5.v-bind dynamic binding style (object syntax)

6.v-bind dynamic binding style (array syntax)


1. Interpolation operation

1.Mustache syntax

​ Mustache means beard, because { {}}it is like a beard, also called braces syntax.

​ In the dom element mounted by the vue object, { {}}not only variables can be written directly, but simple expressions can also be written.

<body>    
    <div id="app">
        <h2>{
   
   {message}}</h2>
        <h2>{
   
   {message}},world</h2>
     <!-- Mustache的语法不仅可以直接写变量,还可以写简单表达式 -->
        <h2>{
   
   {firstName+'-'+lastName}}</h2>
        <h2>{
   
   {firstName}}-{
   
   {lastName}}</h2>
        <h2>{
   
   {firstName+lastName}}</h2>
        <h2>{
   
   {count*2}}</h2>
    </div>
    <script>
        Vue.config.productionTip = false;  //阻止 vue 在启动时生成生产提示。
        const vm = new Vue({
            el: '#app',
            data(){
                return{
                    message: 'hello',
                    firstName:'zhang',
                    lastName:'san',
                    count:2
                }        
            }
        })
    </script>
</body>

 2. Display of vue list (v-for)

​ Commonly used arrays in development have a lot of data, which need to be displayed in full or in part. In native JS, you need to use for loop traversal to replace div elements in turn. In Vue, you can use simple traversal to generate element nodes v-for.

<div id='app'>
        <!-- <h2>{
   
   {todolists}}</h2> -->
        v-for="数组或对象中的每一个值  in/of  数组或对象本身"

        <!-- <h2 v-for="item in todolists">{
   
   {item}}</h2> -->
        <!-- <h2 v-for="item of todolists">{
   
   {item}}</h2> -->

        <!-- <h2 v-for="item of obj">{
   
   {item}}</h2> -->
        <!-- <h2 v-for="item in obj">{
   
   {item}}</h2> -->

        <h2 v-for="item of obj2">{
   
   {item.a}}{
   
   {item.b}}{
   
   {item.c}}</h2>
        <!-- <h2 v-for="item in obj2">{
   
   {item.a}}{
   
   {item.b}}{
   
   {item.c}}</h2> -->
        <ul>
            <li v-for="item of obj2">{
   
   {item.a}}{
   
   {item.b}}{
   
   {item.c}}</li>
        </ul>

        <!-- 添加索引值    动态绑定key值,涉及diff算法 可以为index、id,
            在将来的项目中写v-for是需要加上:key 它的值可以写索引,最好写数据中的id值-->
        <h2 v-for="(item,index) in todolists" :key="index">{
   
   {item}}--{
   
   {index}}</h2>

        <h2 v-for="item in obj2" :key="item.id">{
   
   {item.a}}{
   
   {item.b}}{
   
   {item.c}}</h2>
			<!-- diff算法 -->
    </div>
    <script>
        Vue.config.productionTip = false;
        const vm = new Vue({
            el: '#app',
            data() {
                return {
                    todolists: ['篮球', '排球', '羽毛球', '足球'],
                    obj: {
                        a: '张三',
                        b: '李四',
                        c: '王五'
                    },
                    obj2: [{
                        id:1,
                        a: '张三'
                    }, {
                        id:2,
                        b: '李四'
                    }, {
                        id:3,
                        c: '王五'
                    }]
                }

            }
        })
    </script>

item represents the currently traversed element, and index represents the element index. In order to give Vue a hint so that it can track the identity of each node so that it can reuse and reorder existing elements, you need to provide a unique attribute for each item  key . v-for It is recommended to provide  attributes when using as much as possible  key , unless traversing the output DOM content is very simple, or deliberately rely on the default behavior for performance improvement.

Because it's a general mechanism for Vue to identify nodes, key it's not  v-for specifically tied to .

Do not use non-primitive values ​​such as objects or arrays  v-for as  key. Please use a string or numeric value. 

3. Vue case-counter

​ Use vue to implement a small counter, click +the button, the counter +1, use -the button counter -1.

  1. Define the vue object and initialize a variable count=0

  2. Define two methods addand subfor count++ or count--

  3. Define two button objects and add a click event to the button

    In the Vue object, methods are used to represent the collection of methods, and the keywords used are used to bind elements to listen for click events, to bind click events to buttons, and to bind callback functions and v-on:clicktrigger events . Expressions can also be used directly in callback methods. For example: and .addsubcount++count--

<body>
    <div id="app">
        <!-- <button type="button" v-on:click="add">+</button>
        <h3>{
   
   {count}}</h3>
        <button type="button" v-on:click="sub">-</button> -->

        <!-- 简写 v-on:click  简写  @click-->
        <button type="button" @click="add">+</button>
        <h3>{
   
   {count}}</h3>
        <button type="button" @click="sum">-</button>

    </div>
    <script>
        /* 点击事件
         v-on 监听事件
         */
        Vue.config.productionTip = false;
        new Vue({
            el: '#app',
            data() {
                return {
                    count: 0
                }
            },
            methods: { //以后所有的vue中的方法都可以写在methods里面
                /*  add:function(){
                     // console.log('add');
                     this.count++;
                 },
                 sub:function(){
                     // console.log('sub');
                     this.count--;
                 } */

                add() {
                    /* console.log(this); */
                    this.count++;
                },
                sub() {
                    this.count--;
                }
            }
        })
    </script>
</body>

 

4. Common command v-once

 ​ v-once means that the DOM element is only rendered once, and after the data changes, it will not be rendered again.

<body>
    <div id="app">
        <h2>{
   
   {msg}}</h2>
        <!-- 只会渲染一次,数据改变不会再次渲染 -->
        <h2 v-once>{
   
   {msg}}</h2>
    </div>
    <script>
        Vue.config.productionTip = false;  //阻止 vue 在启动时生成生产提示。
        const vm = new Vue({
            el:'#app',
				data(){
					return {
						msg:'我就是这么倔强'
					}
				}
        })
    </script>
</body>

After the above { {msg}}msg is modified, the first h2 tag data will automatically change, but the second h2 will not.

5. Common command v-html

​ At some point we don't want to directly output <a href='http://www.baidu.com'>百度一下</a>such a string, but output a hyperlink converted by html itself. At this point you can use v-html.

    <div id="app">
        <h2 v-html="url"></h2>
    </div>
    <script>
        const vm = new Vue({
            el:'#app',
            data(){
                return {
                    url:"<a href='http://www.baidu.com'>百度一下</a>"
                }
            }
        })
    </script>

6. Common command v-text 

​ v-text will overwrite the data in the dom element, which is equivalent to the innerHTML method of js.

  <div id="app">
    <h2>不使用v-text</h2>
    <h2>{
   
   {message}},啧啧啧</h2>
    <h2>使用v-text,以文本形式显示,会覆盖</h2>
    <h2 v-text="message">,啧啧啧</h2>

  </div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el:"#app",
      data:{
        message:"你好啊"
      }
    })
  </script>

​ As shown in the figure, the use { {message}}is to splice variables and strings, but to use v-text to directly cover the string content.

7. Common command v-pre

​ Sometimes we expect to output { {msg}}such a string directly, instead of { {}}the variable value of msg transformed by the syntax, at this time we can use v-prelabels.

<div id="app">
        <h2>不使用v-pre</h2>
        <h2>{
   
   {msg}}</h2>
        <h2>使用v-pre,不会解析</h2>
        <h2 v-pre>{
   
   {msg}}</h2>
    </div>
    <script>
        const vm = new Vue({
            el:'#app',
            data(){
                return {
                    msg:'我比v-once还要厉害'
                }
            }  
        })
    </script>

​ As shown in the figure, the dom decorated with v-pre will directly output the string.

8. Common command v-cloak

 ​Sometimes due to loading delay issues, for example, the card is dropped, and the data is not refreshed in time, which causes the page display to { {message}}change from the message variable "Hello". Such a flickering change will cause a bad user experience. This label needs to be used at this time v-cloak. Before vue parsing, there is v-cloakthis tag in the div attribute, and after vue parsing is complete, the v-cloak tag is removed. Simple, similar to a div starting with a css attribute display:none;, after the loading is complete, the css attribute becomes display:blockand the element is displayed.

<head>
    <meta charset="utf-8" />
    <title>v-cloak指令的使用</title>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <style>
        [v-cloak] {
            display: none !important;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <h2>{
   
   {msg}}</h2>
    </div>
    <script>
        //在vue解析前,div中有一个属性cloak
        //在vue解析之后,div中没有一个属性v-cloak
        setTimeout(() => {
            const vm = new Vue({
                el: '#app',
                data() {
                    return {
                        msg: '你好啊'
                    }
                }
            })
        }, 1000)
    </script>
</body>

​ Here, the state of loading stuck is simulated by delaying for 1 second. As a result, the value of message is not displayed at the beginning, and there is a v-cloak attribute in the div element. After 1 second, the value of the message variable is displayed, and the v-cloak element in div is replaced by remove.

Two, dynamic binding properties

 1. v-bind command

 ​ Sometimes we don't want to put variables in the tag content, like this <h2>{ {msg}}</h2>is to enclose the variable h2 tag, similar to innerHTML of js. But we expect to srcwrite the variable in the following position. If we <img src="src" alt="">want to import the picture like this, we want to dynamically obtain the link of the picture. At this time, the src is not a variable but a string src. If you want to make it effective as a variable, you need to use a tag, v-bind:like this <img v-bind:src="src" alt="">, and Mustache syntax cannot be used here, similarly <img v-bind:src="{ {src}}" alt="">, this is also wrong.

  <div id="app">
      <!-- 错误的做法这里不能使用Mustache语法 -->
      <!-- <img v-bind:src="{
   
   {src}}" alt=""> -->
      <!-- 正确的做法使用v-bind指令 -->
      <img v-bind:src="src" alt="">
      <a v-bind:href="url"></a>

      <img :src="src" />
      <img :src="url" />
  </div>
  <script>
      const vm = new Vue({
         el:'#app',
         data(){
            return {    
               src:'https://cn.bing.com/thid=OIP.NaSKiHPRcquisK2EehUI3gHaE8&pid=Api&rs=1',
               url:'img/6.png'
            }
         }            
     })
  </script>

2. v-bind dynamic binding class (object syntax)

​ Sometimes we expect to dynamically bind the class of the node of the Dom element, and choose whether the Dom has a specified class attribute. For example, add to the h2 tag class="active", when the Dom element has this class, it will turn red <style>.active{color:red;}</style>, write a button binding event, click to turn black, click again to turn red.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>v-bind动态绑定class(对象语法)</title>
  <style>
    .active{
      color:red;
    }
  </style>
</head>
<body>
  <div id="app">
    <!-- <h2 class="active">{
   
   {message}}</h2>
    <h2 :class="active">{
   
   {message}}</h2> -->

    <!-- 动态绑定class对象用法  -->
    <!-- <h2 :class="{key1:value1,key2:value2}">{
   
   {message}}</h2>
    <h2 :class="{类名1:true,类名2:boolean}">{
   
   {message}}</h2> -->
    <h2 class="title" :class="{active:isActive}">{
   
   {message}}</h2>
    <h2 class="title" :class="getClasses()">{
   
   {message}}</h2>
    <button @click="change">点击变色</button>

  </div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el:"#app",
      data:{
        message:"你好啊",
        active:"active",
        isActive:true
      },
      methods: {
        change(){
          this.isActive = !this.isActive
        },
        getClasses(){
          return {active:this.isActive}
        }
      },
    })
  </script>
</body>
</html>

​ Define two variables activeand isActive, used in the Dom element , bound at this time , isActive is true, active display, define method change () bound to the button, click the button , control whether the Dom element has  attributes.:class={active:isActive}class='active'this.isActive = !this.isActiveclass='active'

3. Combination of v-bind and v-for

​ Use v-for and v-bind to implement a small demo, display the movie list, and when you click on a certain movie list, the movie list will turn red.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <style>
        .active {
            color: #f00;
        }
    </style>
</head>
<body>
    <div id="app">
        <ul>
            <!-- <li v-for="(item,index) in movies" :key="index" :class="{active:currentIndex==index}" @click="change(index)">{
   
   {item}}</li> -->
            <li v-for="(item,index) in movies" :key="index" :class="currentIndex==index?'active':''" @click="change(index)">{
   
   {item}}</li><!-- 动态绑定三元表达式 -->
        </ul>
    </div>
    <script>
        const vm = new Vue({
            el: '#app',
            data() {
                return {
                    currentIndex: 0,
                    movies: ["海王", "海贼王", "火影忍者", "复仇者联盟"]
                }
            },
            methods: {
                change(i) {
                    /* 	this.currentIndex = i */
                    if (this.currentIndex == i) return
                    this.currentIndex = i
                }
            }
        })
    </script>
</body>
</html>

​ The index index in v-for, bind event to each row click event, click on the row to get the index index of this row and assign it to, currentIndexuse v-bind:the binding class, when index===currentIndexthe Dom element has an active class, the color turns red. 

4 v-bind dynamic binding class (array usage)

​ An array can be placed in the class attribute, which will be parsed into the corresponding class in turn.

    <div id="app">
        <h2 :class="['active','aaa']">我们正在学习vue</h2>
        <h2 :class="[active,aaa]">我们正在学习vue</h2>
        <h2 :class="getStyle()">我们正在学习vue</h2>
    </div>
    <script>
        /* 数组中加引号和不加引号有区别  
        加引号:表示字符串 是固定的,
        不加引号:表示变量是不固定的 */
        const vm = new Vue({
            el: '#app',
            data() {
                return {
                    active: 'isactive',
                    aaa: 'bbb'
                }
            },
            methods: {
                getStyle() {
                    return [this.active, this.aaa]
                }
            }
        })
    </script>

5.v-bind dynamic binding style (object syntax)

    <div id="app">
        <!-- <h2 :style="{key(属性名):value(属性值)}">{
   
   {message}}</h2> -->
        
        <!-- 加单引号,当成字符串解析 -->
        <h2 :style="{fontSize:'50px'}">我们爱学习</h2>
        
        <!-- 不加单引号,变量解析 -->
        <h2 :style="{fontSize:fontsize}">我们爱学习</h2>
        <h2 :style="getStyle()">我们爱学习</h2>
    </div>
    <script>
        const vm = new Vue({
            el:'#app',
            data(){
                return {
                    fontsize:40+'px'
                }
            },
            methods:{
                getStyle(){
                    return {fontSize:this.fontsize}
                }
            }          
        })
    </script>

6.v-bind dynamic binding style (array syntax)

    <div id="app">
        <h2 :style="[baseStyle]">我们爱学习</h2>
        <h2 :style="['baseStyle']">我们爱学习</h2><!-- 无意义 -->
        <h2 :style="getStyle()">我们爱学习</h2>
    </div>
    <script>
        const vm = new Vue({
            el:'#app',
            data(){
                return {
                  baseStyle:{background:'#f00'}	
                }
            },
            methods:{
                getStyle(){
                    return [this.baseStyle]
                }
            }
        })
    </script>

​ Similar to binding class, binding style is the same.

Guess you like

Origin blog.csdn.net/m0_46461853/article/details/125999136