vue自定义指令
- 回顾
vue指令 : 扩展了html标签属性功能
使用方法 属性写法 v-属性名=“值” - 自定义指令
1 全局
Vue.directive(“指令名”,{ 钩子函数 })
Vue.directive(“指令名”,{
bind(){ },
inserted(el,binding){ },一般使用inserted
update(){ },
unbind(){ }
})
2 局部 只能在注册的组件中使用
let Home = {
direcitves:{
指令名:{钩子函数}
}
}
全局
例1 、自定义指令------自动获取焦点
<body>
<div id="app">
<input type="text" v-focus="100">
</div>
<script>
Vue.directive("focus",{
inserted(el,binding){
console.log(el);//此时的el是input这个标签
el.focus();
console.log(binding)//此时的binding是对象
/*
{name: "focus", rawName: "v-focus", value: 100, expression: "100", modifiers: {…}, …}
*/
}
})
let vm = new Vue({
el:'#app',
data: {
}
})
</script>
例2 自定义指令 -----回到顶部
//css代码
<style>
button{
position:fixed;
bottom:100px;
right:50px;
display: none;
}
</style>
// 布局
<body style="height:2000px">
<div id="app">
<button v-scroll="1000">回到顶部</button>
</div>
</body>
//js代码
<script>
Vue.directive("scroll",{
inserted(el,binding){
//获取传入的值 即binding.value
var scrollTop = binding.value;
//绑定事件(给window)
window.onscroll = function(){
// 获取滚动条滚动距离
var sTop = document.documentElement.scrollTop||document.body.scrollTop;
// 将滚动距离与传入的值作比较
// 滚动距离>传入的值 button显示 否则隐藏
if(sTop>scrollTop){
el.style.display="block"
}else{
el.style.display="none"
}
}
// 给按钮绑定事件
el.onclick = function(){
// window.scrollTo(0,0)
document.documentElement.scrollTop=document.body.scrollTop=0
}
},
//用于提高性能
unbind() {
//如果在inserted里面创建了定时器、或者绑定了全局事件 则需要在这里清除定时器、解绑全局事件
window.onscroll = null
}
})
let vm = new Vue({
el:'#app',
data: {
}
})
</script>
局部
只能在当前实例上使用focus这个指令
let Home = {
directives:{
focus: {
inserted(el,binding){
}
},
unbind() {
}
}
}
过滤器
主要用于模板中,对模板中渲染的数据做一层过滤(对数据做一层简单的修改再输出)
全局
<div id="app">
{{ num | currency}} // 页面显示 ¥107
</div>
<script>
// 定义过滤器 给num自动加¥
Vue.filter("currency",(v)=>{
return "¥"+v;
})
let vm = new Vue({
el:'#app',
data: {
num:107
}
})
</script>
局部
组件的filters属性写过滤器
let vm = new Vue({
el:'#app',
data: {
num:107
},
filters: {
currency:(v)=>{
return "¥"+v;
}
}
})
带默认值的过滤器
<body style="height:2000px">
<div id="app">
{{ num | currency}} //没传值 页面显示 ¥107
{{ num| currency("$")}} //传值 页面显示 $107
</div>
<script>
let vm = new Vue({
el:'#app',
data: {
num:107
},
filters: {
currency:(v,sign="¥")=>{
return sign+v;
}
}
})
</script>