MVC和MVVM关系图解
插值表达式闪烁问题解决
v-cloak 和css标签一起使用#v-cloak
[v-cloak]{
display: none;
}
<div id="app" v-cloak></div>
<div v-cloak>{{ msg }}</div>
v-text
<p>选择的项是:{{ selected }}</p>
<p v-text="selected"></p>
<!--v-text无闪烁问题,会覆盖元素中原本内容 -->
v-html :v-html 会覆盖元素中原本内容,(存在安全问题)
<p v-html="vhtml">1111111111</p>
vhtml:'<p>选择的项是111</p>',
v-pre:显示原始信息,跳过编译过程。
<p v-pre>{{msg}}</p>
v-once:只渲染元素和组件一次。随后的重新渲染,元素/组件及其所有的子节点将被视为 静态内容并跳过。这可以用于优化更新性能。
<p v-once>{{msg}}</p>
v-for
v-bind
用于绑定属性(在数据绑定中,实现单项数据绑定,M -----> V) 缩写:v-bind 绑定class style 实现样式修改
.red{color: red;}
.thin{font-weight: 200;}
.italic{font-style: italic;}
.active{letter-spacing: 0.5em;}
<h1 :class="['red','thin',flag?'active':'',{'italic':incline}]">上天给予他们的恩赐</h1>
<h1 :class="{red:true,thin:true}">上天给予他们的恩赐</h1>
<h1 :class="classobj">上天给予他们的恩赐</h1>
<!-- 直接使用对象 -->
<h1 :style="{color:'red'}">生与死轮回不止</h1>
<h1 :style="styleObj1">生与死轮回不止</h1>
<h1 :style="[styleObj1,styleObj2]">生与死轮回不止</h1>
data: {
flag:true,
incline:true,
classobj:{red:true,thin:true,active:true},
styleObj1:{ color:'red','font-weight':200},
styleObj2:{ 'font-style':'italic'},
},
v-on
事件绑定机制 缩写@
事件修饰符 (可组合使用)
|.stop 阻止冒泡
|.prevent 阻止默认事件
|.capture 添加事件侦听器时使用事件捕获模式
|.self 只当事件在该元素本身(比如不是子元素)触发时触发回调
|.once 事件只触发一次
<input type="button" value="button" v-bind:title="btitle + '123' " v-on:click="clickAlert()">
btitle:"it's title",
clickAlert:function(){
alert(111);
}
事件参数传递
传递普通参数和事件对象
<button type="button" v-on:click="sub('arg1','arg2',$event)">clicksub</button>
sub(i,j,event){
console.log(i,j)
console.log(event)
console.log(event.target.tagName,event.target.innerHTML)
......
}
v-model
双向数据绑定 (只能运用到表单元素中 input,select,checkbox,textarea)实现表单元素和model中数据的双向绑定v-model.lazy绑定的值不实时改变,在失焦和回车后才更新。
v-model.number将输入转换为Number类型
v-model.trim自动过滤输入的首尾空格
<input type="text" v-model.lazy="message"> <!---->
<p>{{ message }}</p>
message:''
双向数据绑定的非v-model实现
v-model的底层实现原理
<input :value="msg" @input="msg=$event.target.value" />
v-if 和 v-show
<input type="button" name="" id="" value="toggle" @click="toggle"/>
<h3 v-if="flag">v-if控制的元素</h3>
<!-- v-if 较高的切换性能消耗,适合条件不经常改变的场景 v-show较高的初始渲染消耗,适用于频繁切换条件-->
<h3 v-else="flag">v-if控制的元素消失了</h3>
<h3 v-show="flag">v-show控制的元素</h3>
<template v-if="type === 'name'"><!-- v-show不能在<template>上使用-->
<label>用户名:</label>
<input type="text" placeholder="输入用户名" key='name-input'>
</template>
<template v-if="type === 'email'">
<label>邮箱:</label>
<input type="text" placeholder="输入邮箱" key='email-input'>
</template>
<button type="button" @click="toggleClick">切换输入</button>
data: {
flag:true,
type:'name',
},
methods: {
toggle(){
this.flag = !this.flag
},
toggleClick(){
this.type = this.type === 'name'?'email':'name';
}
},