Vue教程-Vue语法糖与v-bind绑定CSS样式-学习vue第一站深入浅出(五)

语法糖

v-bind和v-on指令都提供了缩写方式:

v-bind缩写为:“:”

v-on缩写为:“@”

可以动态更新H5元素属性,示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Vue语法糖-示例</title>
	</head>
	<body>
		<div id="app"> 
			<a v-bind:href="url" target="_blank">无语法糖链接</a>
			<img v-bind:src="imgUrl" />
			<p></p>
			<a :href="url" target="_blank">有语法糖链接</a>
			<img :src="imgUrl"/>
		</div>
		<script src="js/vue.min.js"></script>
		<script>
 
			var app = new Vue({
				el:'#app',
				data:{
					url:'https://blog.csdn.net/weixin_43687095',
					imgUrl:'https://img-blog.csdnimg.cn/20190628162508569.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzY4NzA5NQ==,size_16,color_FFFFFF,t_70'
					} 
			})
 
		</script>
	</body>
</html>

在前端工程师的日常工作中,最常用的是动态设置class属性与style样式,方法如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Vue绑定class样式-示例</title>
	</head>
	<style>
	.active {
		width: 100px;
		height: 100px;
		background: red;
	}
	</style>
	<body>
		<div id="app"> 
		<div :class="{'active':isActive}"></div> 
		</div>
		<script src="js/vue.min.js"></script>
		<script>
 
			var app = new Vue({
				el:'#app',
				data:{
					isActive:false
					} 
			})
 
		</script>
	</body>
</html>

运行结果是一个红色方块,说明渲染出的界面是加了active的CSS样式的结果。

也可以在对象中传入更多属性用来动态切换多个 class 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Vue绑定class样式-示例2</title>
	</head>
	<style>
	.active {
		width: 100px;
		height: 100px;
		background: gray;
	}
	.text-danger {
		width: 50px;
		height: 50px;
		background: red;
	}
	</style>
	<body>
		<div id="app"> 
		<div class="sample" :class="{'active':isActive,'text-danger': hasError}"></div> 
		</div>
		<script src="js/vue.min.js"></script>
		<script>
 
			var app = new Vue({
				el:'#app',
				data:{
					isActive:true,
					hasError: true
					} 
			})
 
		</script>
	</body>
</html>
渲染出的页面结果为:<div class="sample active text-danger"></div>

  此外,我们也可以在这里绑定返回对象的计算属性。这是一个常用且强大的模式:

<body>
<div id="app">
  <div v-bind:class="classObject"></div>
</div>
<script>

new Vue({
  el: '#app',
  data: {
    isActive: true,
    error: {
      value: true,
      type: 'fatal'
    }
  },
  computed: {
    classObject: function () {
      return {
  base: true,
        active: this.isActive && !this.error.value,
        'text-danger': this.error.value && this.error.type === 'fatal',
      }
    }
  }
})
</script>
</body>

数组语法

我们可以把一个数组传给 v-bind:class ,实例如下:

<style>
.active {
	width: 100px;
	height: 100px;
	background: green;
}
.text-danger {
	background: red;
}
</style>
</head>
<body>
<div id="app">
	<div v-bind:class="[activeClass, errorClass]"></div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
</script>
</body>

发布了28 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43687095/article/details/94398717