- filter filters
- 全局过滤器(所有组件有效):
Vue.filter(''过滤器名,'过滤函数') - 组件内过滤器(组件内有效):
Vue.filters(''过滤器名,'过滤函数')
- 全局过滤器(所有组件有效):
代码:
<!DOCTYPE html>
<html>
<head>
<title>过滤器</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
var App = {
template:`
<div>
<input type = 'text' v-model:value = 'myText'/>
<br>
过滤后数据为:{{myText | reverse("中文版:") }}
</div>
`,
data:function(){
return {
myText:'',
}
},
filters:{//组件过滤器
reverse:function(dataStr,lang){
//打散成数组 反转 变字符串
return lang + dataStr.split('').reverse().join('');
}
}
};
// 全局过滤器 用法 {{ 'xxx' | myreverse('arg1') }}
Vue.filter('myreverse',function(dataStr,arg1){
return 'cccc';
});
new Vue({
el:'#app',
components:{
app:App,
},
template:'<app/>'
});
</script>
</body>
</html>
watch 单个
- watch和v-model的区别
- v-model仅仅是对数据双向绑定
- watch 对符合匹配规则的数据进行函数处理
- 对复杂数据建议使用computed 计算属性
代码示例
<!DOCTYPE html>
<html>
<head>
<title>Watch</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
var App = {
template:`
<div>
<input type = 'text' v-model:value = 'myText'/>
<br>
{{myText}}
<button @click=" stus[0].name='rose'; "> 对象或数组的监视 </button>
</div>
`,
data:function(){
return {
myText:'',
stus:[{
name:'song',
}],
}
},
watch:{
//obj或array数据类型的监视
stus:{
deep:true,
handler:function(newDV,oldDV){
console.log(newDV,oldDV);
}
},
//简单数据类型的监视
//key是data的属性
myText:function(newV,oldV){
console.log(newV,oldV);
if(newV == 'steven'){
alert('ya ,i am the one');
}
}
}
};
new Vue({
el:'#app',
components:{
app:App,
},
template:'<app/>'
});
</script>
</body>
</html>
computed (计算属性)多个
-
computed:{ 监视的业务名:function(){ return 显示的内容 }}- 使用:
{{ 计算属性的名称 }}
代码示例:
- 使用:
<!DOCTYPE html>
<html>
<head>
<title>Computed</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
var App = {
template:`
<div>
<input type="text" v-model = "n1"/>
+
<input type="text" v-model = "n2"/>
*
<input type="text" v-model = "rate"/>
= {{result}}
</div>
`,
data:function(){
return {
n1:0,
n2:0,
rate:0,
}
},
computed:{
result:function(){
//监视对象,写在函数内部
//凡是函数内部有this.属性,改变都会触发当前函数
//this.n1 this.n2 this.rate
return ((this.n1-0) + (this.n2-0)) * (this.rate-0);
}
}
};
new Vue({
el:'#app',
components:{
app:App,
},
template:'<app/>'
});
</script>
</body>
</html>
总结
- 可全局使用的有:组件/过滤器 (直接用,全局不带s)
- 过滤器:
function(原数据,参数1,参数2){ return 结果 }- 调用:
{{ '数据' | 过滤器名(参数1,参数2) }}
- 调用:
- watch单个监视
- computed 群体监视