关于Vue的不同版本:
1、vue.js和vue.runtime.xxx.js的区别:
1)vue.js是完整版的Vue,包含:核心功能+模板解析器
2)vue.runtime.xxx.js是运行版的Vue,只包含:核心功能,没有模板解析器
2、因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用render函数接收到的createElement函数去指定具体内容
计算属性computed:
当其依赖属性的值发生变化时,这个属性的值会自动更新,与之相关的DOM部分也会同步自动更新。
//计算属性名:function(){
//计算表达式
// return 结果
//}
<body>
<div id="root">
price: <input type="text" v-model.number="price"><br>
count: <input type="number" v-model="count"><br>
total: <input type="text" v-model="total">
</div>
<script>
new Vue({
el:"#root",
data:{
price:10,
count:10
},
computed:{
total:function(){
return this.price*this.count
}
}
})
</script>
</body>
侦听器watch
用来监听data对象属性或者计算属性的变化。
watch:{[key:string]:stirng|Function|Object|Array}
//watch的值是一个对象,对象得的属性是要监听的属性,该属性是
//需要观察的表达式(存放数据的属性),其值
//是回调函数,也可以是方法名,或者是包含选项的对象
<body>
<div id="root">
price: <input type="text" v-model.number="price"><br>
count: <input type="number" v-model="count"><br>
total: <input type="text" v-model="total">
</div>
<script>
new Vue({
el:"#root",
data:{
price:10,
count:10,
total:100
},
watch:{
"price":function(nv,ov){
return this.total = nv * this.count
},
"count":function(nv,ov){
return this.total = nv * this.price
}
}
})
</script>
</body>
watch与computed区别:
计算属性会保存结果,侦听器watch不会;计算属性computed强调的是结果,watch强调的是过程‘;computed处理同步的过程,watch多用于处理耗时的异步过程;computed能做的,watch都能,反之不行,但能用computed尽量用computed。
过滤器filter:
全局过滤器定义在Vue对象,定义的语法为:
Vue.filter('过滤器名称',function(参数列表){函数体})
过滤器只在插值语法和V-bind中调用,添加在表达式的尾部,由“|”分隔:
{{要过滤的数据|过滤器名(参数列表)}}
<body>
<div id="root">
<h1>{{sum|f_test}}</h1>
</div>
<script>
Vue.filter('f_test',function(x){
return Math.round(x);
})
new Vue({
el:"#root",
data:{
sum:90.7
},
})
</script>
</body>
局部过滤器定义在Vue实例的对象上,局部过滤器只有在该Vue实例控制(#root)的页面区域内有效,而全局过滤器对整个页面上的所有Vue实例孔子的页面区域内有效。
<body>
<div id="root">
<h1>{{sum|f_test}}</h1>
</div>
<script>
Vue.filter('f_test',function(x){
return Math.round(x);
})
new Vue({
el:"#root",
data:{
sum:90.7
},
filters:{
f_test(x){
return Math.round(x)
}
}
})
</script>
</body>
局部与全局的名称相同时,局部过滤器优先调用。
ref属性:
1、被用来给元素或子组件注册引用信息(id的替代者)
2、应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
3、使用方式:
打标识:<h1 ref="xxx">.....</h1>或<School ref="xxx"></School>
获取:this.$refs.xxx
配置项props:
功能:让组件接收外部传过来的数据
1)传递数据:
<Demo name="xxx"/>
2)接收数据:
第一种方式(只接收):
props:['name']
第二种方式(限制类型):
props:{
name:String
}
第三种方式(限制类型、限制必要性、指定默认值):
props:{
name:{
type:String,
required:true
default:'zs'
}
}
备注:props是只读,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props中的内容到data中一份,然后去修改data中的数据。
mixin(混入):
功能:可以把多个组件共用的配置提取成一个混入对象
使用方式:
1)定义混入
2)使用混入:
全局混入:Vue.mixin(xxx)
局部混入:mixins:['xxx']