Vue(1)插值操作|青训营笔记

92 阅读1分钟

这是我参与「第四届青训营 」笔记创作活动的的第5天

1、插值操作

1.1 Mustache语法-->{{}} 双大括号

  • 在Mustache语法中,不仅可以直接写变量,也可以写简单的表达式

    {{message}}
    {{firstName + lastName}}
    

1.2 v-once

  • 该指令后面不需要跟任何表达式(比如之前的v-for后面是有表达式的)
  • 该指令表示元素和组件只渲染一次,不会随着数据的改变而改变
 <body>
     <div id="app">
       <h1>{{counter}}</h1>
       <h1 v-once>{{counter}}</h1>
     </div>
     <script>
       const app = new Vue({
         el: '#app',
         data: {
           counter:'hello world'
         }
       })
       // Vue.createApp(App).mount('#app');
     </script>
   </body>

1.3 v-html

  • 某些情况下,我们从服务器请求到的数据本身就是一个HTML代码
  • 如果我们直接通过{{}}来输出,会将HTML代码也一起输出
  • 但是我们希望输出解析后的内容

使用v-html指令

<body>
		<div id="app">
			<h1 v-html="url"></h1>
			<!-- <h1 v-once>{{counter}}</h1> -->
		</div>
		<script>
			const app = new Vue({
				el: '#app',
				data: {
					counter:'hello world',
					url: "<a href = 'http://www.baidu.com'>百度一下</a>"
				}
			})
		</script></body>

2、v-bind

2.1 引入

  • 前面我们学习的指令主要作用是将值插入到我们的模版内容中

  • 但是除了内容需要动态来决定外,某些属性我们也希望动态来绑定

    --比如动态绑定a元素的href属性

    --比如动态绑定img元素的src属性

  • 这时我们可以使用v-bind指令

  • 作用:动态绑定属性

  • 缩写: :

  • 预期:any(with argument)|Object(without arguement)

  • 参数:attrOrProp(optional)

2.2 基本使用

<body>
    <div id="app">
      <!-- 错误使用 这里不能使用mustache语法 -->
      <!-- <img src="{{imgUrl}}"/> -->
      <img v-bind:src="imgUrl" />
      <a v-bind:href="link">百度一下</a>
    </div>
    <script>
      const app = new Vue({
        el: '#app',
        data: {
          counter:'hello world',
          imgUrl:'https://cn.vuejs.org/images/logo.svg',
          link:'http://www.baidu.com'
        }
      }) 
      // Vue.createApp(App).mount('#app');
    </script>
  </body>

在开发中,我们通常会使用语法糖的形式,因为这样更加简洁

2.3 v-bind语法糖(简写)

<div id="app">
  <a :href = "link">官网</a>
  <img :src = "logoUrl"/>
</div>

2.4 v-bind动态绑定class

2.4.1 对象语法

<body>
  <style>
  .active{
    color:red;
  }
  </style>
  <div id="app">
    //动态绑定class属性
    <!--<h2 :class = "{key1(类名1): value1, key2(类名2): value2}">{{message}}</h2>-->
    <h2 :class="{active:isActive,line:isLine}">{{message}}</h2>
  </div>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        message:'hello',
        //用来控制是否拥有此属性
        isActive:true,
        isLine:true
      }
    })  
  </script>
</body>

2.4.2 数组语法

<body>
		<style>
		.active{
			color:red;
		}
		.aaaa{
			color: pink;
		}
		</style>
		<div id="app">
			<h2 :class="getClass()">{{message}}</h2>
		</div>
		<script>
			const app = new Vue({
				el: '#app',
				data: {
					message:'hello',
					active:'aaaa',
					line:'bbb'
				},
				methods:{
					getClass:function(){
						return [this.active,this.line];
					},
				}
			}) 
			// Vue.createApp(App).mount('#app');
		</script>
	</body>

2.5 v-for

     <li v-for = "变量 in 列表">{{m}}</li>