Vue学习4 - 自定义指令、回调函数、箭头函数

x33g5p2x  于2022-02-12 转载在 Vue.js  
字(2.2k)|赞(0)|评价(0)|浏览(455)

1. 自定义指令

自定义指令时需要使用到钩子函数进行定义指令

钩子函数bind:只调用一次,进行初始化操作inserted:被绑定元素父节点插入时的调用updatecomponentUpdatedunbind:只调用一次,指令与元素解绑时
钩子函数的参数el:被绑的元素对象binding:被绑指令所传的值 - 用来描述指令vnodeoldVnode

全局指令

一进入界面输入框自动被选中

<body>
    <div id="vueBox">
       <input type="text" v-input_focus>
    </div>
</body>

<script type="text/javascript">

    Vue.directive('input_focus', {
        inserted: function(el, binding) {
            el.focus();
            console.log( binding.value)
        }
    })

    var vue = new Vue({
        el: "#vueBox",
        data: {
            msg: '刷新即被选中'
        }
    })

</script>

局部指令

<body>
    <div id="vueBox">
       <input type="text" v-input_focus="msg">
    </div>
</body>

<script type="text/javascript">

    var vue = new Vue({
        el: "#vueBox",
        data: {
           msg: '刷新即被选中'
        },
        methods: {
            a(event, a) {
                console.log(event);
                console.log(a);
            }
        },
        directives: {
            input_focus: {
                inserted: function(el, binding) {
                    el.focus();
                    console.log(binding.value)
                }
            }
        }
    })

</script>

2. 过滤器

用于格式化数据 - 使用时可传参–类似函数调用*
语法: {{ date属性名 | 过过滤器名 }} 以及在 v-bind:属性="data属性名 | 过滤器"

*全局过滤器

<body>
    <div id="vueBox">
       <input type="text" v-model="msg">
        <p>{{msg | filter}}</p>
    </div>
</body>

<script type="text/javascript">

   Vue.filter("filter", function(val) {
       return val.charAt(0).toUpperCase() + val.slice(1);
   })

    var vue = new Vue({
        el: "#vueBox",
        data: {
           msg: 'fd'
        },
        methods: {

        },

    })

</script>

*局部过滤器

<script>
   var vue = new Vue({
        el: "#vueBox",
        data: {
           msg: 'fd'
        },
        methods: {

        },
        filters: {
            filter: function(val, args) {
                console.log( args );
                return val.charAt(0).toUpperCase() + val.slice(1);
            }
        }

    })
</script>

3. 回调函数中是普通函数、箭头函数this指向问题

回调函数是:

  1. 箭头函数this指向父级对象
  2. 普通函数this指向window对象
<body>
    <div id="vueBox">
        <button v-on:click="test1">window对象</button>
        <button v-on:click="test2">vue对象</button>
    </div>
</body>

<script type="text/javascript">

    var vue = new Vue({
        el: "#vueBox",
        data: {
            nums: [1,2,3,4]
        },
        methods: {
          test1: function() {
              this.nums.some(function(item) {
                  if(item == 1) {
                      console.log(this);
                  }
              })
          },
          test2: function() {
            this.nums.some((item) => {
                if(item == 1) {
                    console.log(this);
                }
            })
          }
        }
    })

</script>

相关文章

微信公众号

最新文章

更多