manlili blog

Vue入门演示

研究下最近很流行的vue,写几个测试代码
github地址:https://github.com/manlili/vue_learn里面的lesson01
目录如下:
图

单向数据绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>vue</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<script src="js/vue.js"></script>
</head>
<body>
<div class="test">
{{message}}
</div>
<script>
var vue = new Vue({
el: ".test", //必须有el
data:{
message:"这是个测试"
}
})
</script>
</body>
</html>

双向数据绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue双向数据成功</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<script src="js/vue.js"></script>
</head>
<body>
<div class="test"> <!--注意文本和input要在同一个el下面,要不然input输入改变不了p里面内容-->
<p>{{message}}</p>
<input type="text" v-model="message">
</div>
<script>
var vue = new Vue({
el: ".test", //必须有el
data:{
message:"这是个测试"
}
})
</script>
</body>
</html>

访问数组数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue数组</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<script src="js/vue.js"></script>
</head>
<body>
<ul class="test" v-for="item in message">
<li>{{item}}</li>
</ul>
<script>
var vue = new Vue({
el: ".test", //必须有el
data:{
message:["aa","bb","cc"]
}
})
</script>
</body>
</html>

访问数组中对象数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue数组中对象</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<script src="js/vue.js"></script>
</head>
<body>
<ul class="test" v-for="item in message">
<li>{{item.name}}</li>
</ul>
<script>
var vue = new Vue({
el: ".test", //必须有el
data:{
message:[{name:"lili"},{name:"haha"},{name:"kkkk"}], //注意此处name这个key值必须保持一致,要不然数组循环没法访问不同的key值
}
})
</script>
</body>
</html>

vue方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue方法</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<script src="js/vue.js"></script>
</head>
<body>
<div class="test">
<p class="pp">{{message}}</p>
<button @click="changeColor">使用vue方法</button>
</div>
<script>
var vue = new Vue({
el: ".test", //必须有el
data:{
message:"这是个测试"
},
methods:{
changeColor:function () {
document.getElementsByClassName("pp")[0].style.color="#ff0000";
}
}
})
</script>
</body>
</html>
请我喝杯果汁吧!