vue指令
1、 v-html 指令的作用
-
在设置元素的innerHTML
-
内容中有html结构会被解析为标签
-
v-text指令无论内容是什么,只会解析为文本
<div id="app"> <p v-html="content"></p> <p v-text="content"></p> <p v-pre>{{msg}}</p> <!-- {{}}相当于原样输出 -- </div>
<script> let app = new Vue({ el: '#app', data: { msg:"哈哈哈", // content:"我是百度", content: "<a href='#'> 我是百度</a>" } }) </script>
2、 v-bind 指令的作用
-
v-bind指令的作用是:为元素绑定属性
-
完整写法是v-bind:属性名
-
简写的话可以直接省略v-bind,只保留:属性名
<div id="app"> <img v-bind:src="imgSrc"> <img :src="imgSrc" :title="imgTitle" :class="{active:isactive}" @click="changesActive"> </div>
<script> let app = new Vue({ el: "#app", data: { imgSrc: "https://img0.baidu.com/it/u=3122136587,3938996930&fm=26&fmt=auto", imgTitle: '图片标题', isactive: false, }, methods: { changesActive: function () { this.isactive = !this.isactive } } }) </script>
3、 v-text 指令的作用
-
v-text指令的作用是:设置标签的内容(textContent)
-
默认写法会替换全部内容,使用插值表达式{份}可以替换指定内容
<div id="app"> 程序员{{message+'哈哈哈'}} <p v-text="info"></p> <!-- <p v-text="info" +'世界'></p> --> <!-- v-text 不能设置字符串的拼接 --> </div>
<script> let app = new Vue({ el: '#app', data: { message: 'hello vue', info: '你好呀', } })v-cloak </script>
4、 v-pre 指令的作用
不识别插值表达式
5、 v-cloak 指令的作用
v-cloak 这个属性对应的元素会在vue运行的时候,把这个属性去掉,也就是可以用v-cloak 解决插值表达式闪烁问题
<div id="app" v-cloak>
<p>{{msg}}</p>
</div>
<script>
let app = new Vue({
el: "#app",
data: {
msg: "cloak清除闪烁效果 ",
}
})
</script>
6、 v-on指令的作用
为元素绑定事件事件名不需要写on
指令可以简写为@
绑定的方法定义在methods属性中
<div id="app">
<input type="button" value="v-on指令" v-on:click="doit">
<input type=utton" value="v-on指令简写" @click='doit'>
<input type="button" value="双击事件" @dblclick='doit'>
<h2 @dblclick='changesFoods'>{{food}}</h2>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
food: "米饭"
},
methods: {
doit: function () {
alert('hhh')
},
changesFoods: function () {
// console.log(this.food);
this.food += '很好吃'
}
} })
</script>
7、 v-on指令的作用
-
根据表达式的真假切换元素的显示状态
-
本质是通过操纵dom元素来切换显示状态
-
表达式的值为true,元素存在于dom树中,为false,从dom树中移除
-
频繁的切换使用v-show,反正使用v-if,前者的切换消耗少
<div id="app">
<input type="button" value="点击显示隐藏" @click="changesShow">
<p v-if='isShow'>今天又是美好的一天</p>
<p v-show='isShow'>出去逛逛</p>
<h3 v-if='temper>35'>天气好热呀</h3>
<!-- 简单的表达式 -->
</div>
<script>
let app = new Vue({
el: "#app",
data: {
isShow: false,
temper:25
},
methods: {
changesShow: function () {
this.isShow = !this.isShow
}
}
})
</script>
绑定事件
样式绑定
1. class绑定
可以传给 v-bind:class
一个对象,以动态地切换 class
<div id="app">
<div v-bind:class="{box:flag}" style="width: 100px; height: 100px;">
hello,Vue
</div>
</div>
<script>
let app = new Vue({
el: "#app",
data: {
flag: true,
}
});
</script>
2. style绑定
用 对象的方式,直接将具体样式绑定
<div id="app">
<div :style="{color:color,fontSize:size}">
hello,Vue
</div>
</div>
<script>
let app = new Vue({
el: "#app",
data: {
color: "blue",
size: "60px"
}
})
</script>