一、vue常用指令
1.v-for指令:用于迭代字符串
效果图:
源码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-for指令</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="food in foodList">{{food.name}}:¥{{food.discount? food.price*food.discount : food.price}}</li>
</ul>
</div>
<script src="lib/vue.js"></script>
<script src="js/v-for.js"></script>
</body>
</html>
v-for.js:
var app = new Vue({
el: '#app',
data: {
//foodList: ['葱', '姜', '蒜'],
foodList: [
{
name: '葱',
price: 10,
discount: 0.8,
},
{
name: '姜',
price: 8,
discount: 0.5,
},
{
name: '蒜',
price: 7,
}
]
}
});
2.v-bind指令:用来绑定数据和元素属性,简写为:
效果图:点击点我,跳转到百度页面
源码:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-bind指令</title>
<style>
.active {
background: plum;
}
</style>
</head>
<body>
<div id="app">
<a :class="{active: isActive}" :href="url">点我
<!--<img v-bind:src="img" alt="">-->
</a>
</div>
<script src="lib/vue.js"></script>
<script src="js/v-bind.js"></script>
</body>
</html>
v-bind.js:
var app = new Vue({
el: '#app',
data: {
url:'http://baidu.com',
img: '../bg.jpg',
klass: 'btn btn-default',
isActive: true,
}
});
3.v-on指令:绑定事件,简写为@
效果图:当鼠标入点我按钮时,控制台会显示enter,点击提交按钮时,会显示submit
源码:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-on指令</title>
</head>
<body>
<div id="app">
<button v-on="{mouseenter:onEnter, mouseleave:onOut}" @click="onClick">点我</button>
<form @keyup.enter="onEnter" @submit.prevent="onSubmit">
<input type="text">
<button type="submit">提交</button>
</form>
</div>
<script src="lib/vue.js"></script>
<script src="js/v-on.js"></script>
</body>
</html>
v-on.js:
var app = new Vue({
el: '#app',
methods: {
onClick: function() {
console.log('111');
},
onEnter: function() {
console.log('mouse enter');
},
onOut: function() {
console.log('mouse leaver')
},
onSubmit:function() {
console.log('submited')
},
onEnter:function() {
console.log('enter')
}
}
});