例1:简单展示数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">
<h1>{{message}}</h1>
<h2>hello {{name}}</h2>
</div>
<script>
//let:定义变量(可重新赋值) & const:定义常量(不可重新赋值)
const app = new Vue({
el:'#app', //用于挂载要管理的元素
data:{ //定义数据
message:'hello vuejs',
name:'key'
}
})
</script>
</body>
</html>
展示界面:
例2:列表展示数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>列表展示</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">
<h2>{{message}}</h2>
<ul>
<li v-for="item in name">{{item}}</li>
</ul>
</div>
<script>
const app = new Vue({
el:'#app',
data:{
message:'welcome',
name:['小明','小黑','小红','小白','小小','肖肖']
}
})
</script>
</body>
</html>
展示界面:
还可以在浏览器按F12控制台修改数据:app.name.push('sean')
例3:计数器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计数器</title>
</head>
<body>
<div id="app">
<h2>当前计数:{{counter}}</h2>
<button v-on:click="add">+</button>
<button v-on:click="sub">-</button>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
counter:0
},
methods:{
add:function () {
console.log('add被执行');
this.counter++
},
sub:function () {
console.log('sub被执行');
this.counter--
}
}
})
</script>
</body>
</html>
效果展示: