什么是 Vue?
我们要把一个 json对象的数据,显示到一个元素上去。
如果不使用 Vue, 那么就会用到 JS 或者 JQuery,通过操作 HTML DOM 的方式,把数据显示上去。
如果使用Vue, 那么仅仅需要提供数据,以及数据要绑定到的元素的id,就行了,不需要显式地操作HTML DOM。
简单使用:
<div id="div1">
{{gareen.name}}
</div>
<script>
//json准备数据
var gareen = {"name":"盖伦","hp":616};
//通过vue.js 把数据和对应的视图关联起来
new Vue({
el: '#div1',//对应的控件
data: {
message: gareen
}
})
</script>
监听事件:
<div id="div1">
<div>一共点击了 {{clickNumber}}次</div>
<button v-on:click="count">点击</button>
<button @click="count">点击2</button>
</div>
<script>
new Vue({
el: '#div1',
data: {
clickNumber:0
},
methods:{
count: function(){
this.clickNumber++;
}
}
})
</script>
事件修饰符:.stop .prevent .capture .self .once
在me上的click后面加一个 .stop, 那么冒泡到了这里就结束了,就不会冒到father上面去了。
<div id="me" v-on:click.stop="doc">
在father 上增加一个.capture
<div id="father" v-on:click.capture="doc">
那么当冒泡发生的时候,就会优先让father捕捉事件
<div id="father" v-on:click.self="doc">
这样点击son 和 me都不会导致其触发click事件,只有点击father自己,才会导致事件发生
<div id="father" v-on:click.once="doc">
这样father点击一次之后,就不会再监听到click了,但是,grandFather还能监听到
@click.prevent="jump"、@click.prevent 可以阻止页面刷新。。只有超链和form这种会导致页面刷新的操作,.prevent 才有用。 普通的不导致页面刷新的按钮,加上这个没有任何变化
v-for循环遍历,第一种不带下标,第二种带有下标
<!-- <tr v-for="hero in heros">
<td>{{hero.name}}</td>
<td>{{hero.hp}}</td>
</tr> -->
<tr v-for="hero,index in heros">
<td>{{index+1}}</td>
<td>{{hero.name}}</td>
<td>{{hero.hp}}</td>
</tr>
纯数字遍历:
扫描二维码关注公众号,回复:
3257021 查看本文章
<div id="div1">
<div v-for="i in 10">
{{ i }}
</div>
</div>
<script>
new Vue({
el: '#div1'
})
</script>
过滤器
<td align="center">
<input v-model= "dat" />
</td>
<td align="center">
{{ dat|filter1}}
</td>
<script type="text/javascript">
new Vue({
el: '#div1',
data: {
dat:''
},
filters:{
filter1:function(value) {
if (!value) return '' //如果为空,则返回空字符串
value = value.toString()
return value.charAt(0).toUpperCase() + value.substring(1)
}
}
})
</script>
全局过滤器
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
Vue.filter('capitalizeLastLetter', function (value) {
if (!value) return '' //如果为空,则返回空字符串
value = value.toString()
return value.substring(0,value.length-1)+ value.charAt(value.length-1).toUpperCase()
})