Vue.js 样式绑定
Vue.js class
class 与 style 是 HTML 元素的属性,用于设置元素的样式,可以用 v-bind 来设置样式属性。
class 属性绑定
为 v-bind:class 设置一个对象,从而动态的切换 class:
实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<style>
.active {
width: 150px;
height: 150px;
background: blue;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="{ 'active': isActive }"></div>
</div>
<script>
new Vue({
el: '#app',
data: {
isActive: true
}
})
</script>
</body>
</html>
上述实例中将 isActive 设置为 true 显示了一个蓝色的 div 块,如果设置为 false 则不显示
可以把一个数组传给 v-bind:class ,实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<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>
</html>
Vue.js style(内联样式)
可以在 v-bind:style 直接设置样式
<div id="app">
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">Vue初步</div>
</div>
可以直接绑定到一个样式对象
<div id="app">
<div v-bind:style="styleObject">Vue初步</div>
</div>
v-bind:style 可以使用数组将多个样式对象应用到一个元素上
<div id="app">
<div v-bind:style="[baseStyles, overridingStyles]">Vue初步</div>
</div>
注意:当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。
Vue.js 事件处理器
事件监听可以使用 v-on 指令:
实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<button v-on:click="counter += 1">增加 1</button>
<p>这个按钮被点击了 {{ counter }} 次。</p>
</div>
<script>
new Vue({
el: '#app',
data: {
counter: 0
}
})
</script>
</body>
</html>
需要使用一个方法来调用 JavaScript 方法。v-on 可以接收一个定义的方法来调用。也可以用内联 JavaScript 语句。
<div id="app">
<!-- `greet` 是在下面定义的方法名 -->
<button v-on:click="greet">Greet</button>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
name: 'Vue.js'
},
// 在 `methods` 对象中定义方法
methods: {
greet: function (event) {
// `this` 在方法里指当前 Vue 实例
alert('Hello ' + this.name + '!')
// `event` 是原生 DOM 事件
if (event) {
alert(event.target.tagName)
}
}
}
})
// 也可以用 JavaScript 直接调用方法
app.greet() // -> 'Hello Vue.js!'
</script>
<div id="app">
<button v-on:click="say('hi')">Say hi</button>
<button v-on:click="say('what')">Say what</button>
</div>
<script>
new Vue({
el: '#app',
methods: {
say: function (message) {
alert(message)
}
}
})
</script>