vue---3

97 阅读1分钟
  • 过滤器和渲染优化
    - | 过滤器的管道符 -
    
    <h1>{{'我真的是卷王,我24小时坐在电脑旁'|fn('宝贝')|fn('亲爱的')}}</h1>
    
    <h1>{{'我爱张sir你是我的好老师'|str('金牌讲师')}}</h1>
   
   <h1>{{msg|dao}}</h1>
<script src="./vue.min.js"></script>

<script>
     
     全局过滤器 
    Vue.filter('fn',function(v,s){
         v就是管道符左边的数据 */
        // console.log(v.indexOf(','))
        // return v.substring(0,v.indexOf(','))
        return v+s;
    })

    /* 利用过滤器 把 hello 变成 olleh */
    new Vue({
        el:"#app",
        data:{
            msg:'hello'
        },
        /* 局部过滤器 */
        filters:{
            str:function(v,s){
                return v + s;
            },
            dao:function(v){
                return v.split('').reverse().join('')
            }
        }
    })
</script>
  • 自定义指令
    <input type="text" v-focus="{background:'yellow'}">
    
    <!-- <input type="text" v-bg>
    <input type="text" v-bg>
    <div style="width: 100px;height: 30px;border:1px solid #ccc;" v-bg>

    </div> -->
    <!-- 元素身上使用驼峰命名的属性 fontSize 在浏览器编译元素身上的属性的时候会转化为小写fontsize
    导致两者的名字不一致 从而作用不生效 -->
    <p v-fontsize="{fontSize:'50px'}" v-sty="{background:'red',color:'yellow'}">我是kw47的卷王</p>
</div>
<script src="./vue.min.js"></script>
<script>
    /* 全局自定义指令 简写方式 (不适用于focus()方法 )*/
    /* 定义指令要方法实例化Vue对象的前面 */
    // Vue.directive('focus',function(el){
    //     /* 回调的第一个参数就是元素本身 */
    //     console.log(el)
    //     el.style.background="red"
    // })

    /* 全局自定义指令 全面的写法 */
    Vue.directive('focus',{
        /*  当绑定元素插入到 DOM 中 */
        inserted:function(el,binding){
            console.log(binding)
            el.focus();
            el.style.background = binding.value.background;
        }
    })

   
    /* 全局定义一个自定义指令v-focus 让加上v-focus的input框可以 自动获取焦点 */
    
    new Vue({
        el:"#app",
        /* 局部的自定义指令 */
        directives:{
            fontsize:{
                inserted:function(el,binding){
                    console.log(binding)
                    el.style.fontSize = binding.value.fontSize;
                }
            },
            sty(el,binding){
                el.style.color = binding.value.color;
                el.style.background = binding.value.background;
            }
        }
    })
    /* 使用局部自定义指令v-sty 实现 你传入的color background 加了自定义指令的元素能变成相对应的样式 */
       
</script>
  • 组件
组件(Component)的概念:组件即自定义控件组件的用途:组件能够封装可重用代码,扩展HTML标签功能组件的本质:自定义标签组件的分类全局组件作用域:不同作用域内均可使用局部组件作用域:只在定义该组件的作用域内可以使用注意:组件和Vue实例类似,需要注册后才可以使用
 <div id="app">
    
    <div>
        <child-a />
    </div>
    -- 所有的组件都需要使用一个div来包裹 -
    <div>
        <child-b />
    </div>
</div>
<!-- <template id="ChildA">
    <div>
        <h1>我是ChildA</h1>
    </div>
</template> -->
<!-- 模板的第二种写法 使用template加id -->
<template id="ChildB">
    
    <!-- template里面也需要使用div来包裹一下 -->
    
    <div>
        <h1>我是ChildB</h1>
        <h1>我是ChildB</h1>
        <h1>我是ChildB</h1>
        <h1>我是ChildB</h1>
   
   </div>