双向数据绑定
v-model="message"
数据列表循环
v-for="value in arrName" {{ value }}
过滤器
filters: { methodName: function(value,arg1,arg2...){...} }
过滤器的第一个参数就是写在html里前面的值
过滤器:`{{ message | filter (参数1, 参数2) }}`
过滤器串联:` {{ message | filterA | filterB }} 先执行filterA,然后执行filterB`
var vm = new Vue({
el: '#app',
data: {
float_number: 12.34
},
filters: {
toInt: function (value) {
return parseInt(value);
},
add: function (value,arg1,arg2,arg3) {
var arg1 = arg1||0;
var arg2 = arg2||0;
var arg3 = arg3||0;
return value * 5 +arg1+arg2+arg3;
}
}
})
指令
- 绑定字符串:
v-text="" {{ ... }}
- 解析绑定html内容:
v-html="" {{{ ... }}}
- 绑定事件:
v-on:click="method" @click="method"
方法后面可以加括号和参数,如果没有加括号,在js里写参数就是event事件参数
- 修饰符:
v-on:click.prevent="method" 取消默认行为=e.preventDefault()
- 绑定html属性:
v-bind:href="url" <a v-bind:href="url">link</a>
- 逻辑判断:
v-if="boolean"
v-else-if="boolean"
v-else```
这三个一起使用须在紧邻的标签
v-show="boolean" v-else
* 数组列表渲染
<li v-for="item in items"></li> ``` 在 v-for 块中,我们拥有对父作用域属性的完全访问权限。 v-for 还支持一个可选的第二个参数为当前项的索引。 你也可以用 of 替代 in 作为分隔符,因为它是最接近 JavaScript 迭代器的语法: <div v-for="item of items"></div>
Template v-for 如同 v-if 模板,你也可以用带有 v-for 的 <template> 标签来渲染多个元素块。例如:
<ul>
<template v-for="item in items">
<li>{{ item.msg }}</li>
<li class="divider"></li>
</template>
</ul>
计算属性 computed
// 属性计算:int_number不和filter一样当作方法来使用,而是当作属性
// int_number 会随着float_number的变化而变化
var vm = new Vue({
el: '#app',
data: {
float_number: 12.34
},
computed: {
// 仅读取
int_number: function() {
// this就是指的vm
return parseInt(this.float_number);
},
// 读取和设置
aPlus: {
// 读取
get: function() {
return parseInt(this.float_number);
},
// 设置
set: function(val) {
this.float_number = val;
}
}
}
})
默认使用的getter,可以自己设置setter
计算属性可以根据data属性源的变化自动缓存,依赖数据不变化,就不重复计算,可以依赖多个data里的数据,而methods里面的方法是每次都会运行一次,filters也是
绑定class
<div id="app">
<!--这里的key加不加引号都一样-->
<div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
<!--与普通的class共存-->
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }" ></div>
<!--直接绑定一个对象-->
<div v-bind:class="classObject"></div>
<!--数组语法-->
<div v-bind:class="[activeClass, errorClass]"></div>
<!--表达式-->
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
<!--混合写法-->
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
</div>
<script>
// 使用:{{ message }}
// {{}}可以写简单的表达式 注意:只能写单行不能写多行
// 条件语句不适用,三元表达式可以用
var vm = new Vue({
el: '#app',
data: {
isActive: true,
hasError: false,
classObject: {
active: true,
'text-danger': false
},
activeClass: 'active',
errorClass: 'text-danger'
}
})
</script>
数据列表 for-in
循环数组,第一个参数是对应的值,第二个参数是索引
<li v-for="(value, index) in array"></li>
数组里的每一项
<li v-for="value in array"></li>
循环对象,第一个参数是值,第二个是名,第三个是索引
<li v-for="(value, key, index) in object"></li>
循环对象里的每一个值
<li v-for="value in object"></li>