data数据对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id="app">
{{message}}
<h2>{{user.name}} {{user.password}}</h2>
<ul>
<li>{{ campus[0] }}</li>
<li>{{ campus[1] }}</li>
<li>{{ campus[2] }}</li>
</ul>
</div>
<script>
var app = new Vue({
el:"#app",
data:{
message:"你好xiaokuang!",
user:{
name:"xiaokuang",
password:"123"
},
campus:["北京","天津","南京"]
}
})
</script>
</body>
</html>
Vue指令指的是以V-开头的语法
V-text 设置标签的文本值(textContent)
<body>
<div id="app">
{{message}}
<h2 v-text="message+'!'">深圳</h2>
<h2 v-text="info">深圳</h2>
<h2>{{message}}深圳</h2>
</div>
</body>
<script>
var app = new Vue({
el:"#app",
data:{
message:"你好xiaokuang!",
info:"前端教研部"
}
})
</script>
如果是部分替换就使用两个大括号,
指令可以使用字符串拼接
v-html 设置标签的innerHTML
他和v-text的区别
v-on指令 为元素绑定事件
在vue中不需要考虑怎么拿到dom元素,因为在vue中数据时同步更新的,你只要知道怎么去更改数据就ok
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<body>
<div id="app">
<input type="button" value="v-on指令" v-on:click="doIt">
<input type="button" value="v-on指令简写" @click="doIt">
<input type="button" value="双击事件" @dblclick="doIt">
<h2 @click="changeFood">{{food}}</h2>
</div>
</body>
<script>
var app = new Vue({
el:"#app",
data:{
message:"你好xiaokuang!",
food:"西红柿"
},
methods:{
doIt:function(){
alert("做it");
},
changeFood:function(){
console.log(this.food);
this.food+="好好吃"
}
}
})
</script>
v-show 指令:根据表达式的真假,切换元素的显示和隐藏
true为显示 false为影藏
<body>
<div id="app">
<input type="button" value="求换显示状态" @click="changeisshow">
<input type="button" value="添加年龄" @click="addAge">
<img src="./img/图片1.gif" alt="" v-show="isshow">
<img src="./img/图片1.gif" alt=""v-show="age>18">
</div>
</body>
<script>
var app = new Vue({
el:"#app",
data:{
isshow:"false",
age:17
},
methods:{
changeisshow:function(){
this.isshow = !this.isshow;
},
addAge:function(){
this.age++;
}
}
})
</script>
v-if 指令:根据表达式的真假,切换元素的显示和隐藏(操作dom元素)
v-if和和 v-show的区别
频繁切换用v-show反之v-if
v-if指令的作用是:根据表达式的真假切换元素的显示状态,本质是通过操纵dom元素来切换显示的
v-bind指令 设置class 和 src title
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<body>
<div id="app">
<img v-bind:src="imgSrc" alt="">
<img :src="imgSrc" :title="imgTitle" alt=""
:class="isActive?'active':''" @click="toggleActive">
<br>
<img :src="imgSrc" alt="" :class="{active:isActive}" @click="toggleActive">
</div>
</body>
<script>
var app = new Vue({
el:"#app",
data:{
imgSrc:"https://img.alicdn.com/tfs/TB13DzOjXP7gK0jSZFjXXc5aXXa-212-48.png",
imgTitle:"alibaba",
isActive:false
},
methods:{
toggleActive:function(){
this.isActive = !this.isActive
}
}
})
</script>
</html>