昨天学习了vue的简单实用,今天来看一下vue的指令。
指令带有前缀 v-
,以表示它们是 Vue 提供的特殊 attribute。可能你已经猜到了,它们会在渲染的 DOM 上应用特殊的响应式行为。
一、v-bind
代码示意如下:
<!DOCTYPE html>
<html>
<head>
<title>v-bind</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="test">
<span v-bind:title="message">
将鼠标悬停在这
</span>
</div>
</body>
<script>
var test = new Vue({
el: '#test',
data: {
message: '页面加载于' + new Date().toLocaleDateString()
}
})
</script>
</html>
效果:
二、v-if
代码示例:
<!DOCTYPE html>
<html>
<head>
<title>v-bind</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="test">
<span v-if="seen">
你能看到我
</span>
<span v-if="seen2">
你看不到我
</span>
</div>
</body>
<script>
var test = new Vue({
el: '#test',
data: {
seen: true,
seen2: false
}
})
</script>
</html>
演示:
三、v-for
代码示例:
<!DOCTYPE html>
<html>
<head>
<title>v-bind</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="test">
<ol>
<li v-for="todo in todos">
{{todo.text}}
</li>
</ol>
</div>
</body>
<script>
var test = new Vue({
el: '#test',
data: {
todos: [
{ text: 'Java从入门到入土' },
{ text: 'MySql从删库到跑路' }
]
}
})
</script>
</html>
演示:
四、v-on
代码示例:
<!DOCTYPE html>
<html>
<head>
<title>v-bind</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="test">
<p>{{message}}</p>
<button v-on:click="reverseMessage">反转消息</button>
</div>
</body>
<script>
var test = new Vue({
el: '#test',
data: {
message: 'hello,vue.js'
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
</script>
</html>
效果:
五、v-model
代码示例:
<!DOCTYPE html>
<html>
<head>
<title>v-bind</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="test">
<p>{{ message }}</p>
<input v-model="message">
</div>
</body>
<script>
var test = new Vue({
el: '#test',
data: {
message: 'hellohellohello'
}
})
</script>
</html>
效果: