vue中的for循环以及自定义指令解读

vue for循环及自定义指令

v-for

1.v-for用来循环的数组怎么发生变化可以被vue检测到:

push、pop、shift、unshift、splice、sort、reverse等方法可以被检测到

vue对于这些方法的处理是重写了这些方法,并在最后会触发一次notify方法来通知这个array已经发生变化

vue还增加了两个方法来观测array的变化:

  • $set:如果直接设置array中的元素,不会触发视图的变化
this.selectArray[1] = 'newValue'  // 不会触发视图变化
this.selectArray.$set(1, 'newValue') // 会触发视图变化
  • $remove:是splice的语法糖,用来从目标元素中查找并且删除这个元素
let itemIndex = this.selectArray.indexOf(selectItem)
this.selectArray.splice(itemIndex,1) // 删除这个元素
this.selectArray.$remove(selectItem) // 同样效果,不用查找index

vue不能检测到下面数组的变化:

使用索引设置元素:

this.selectArray[1] = 'newValue'

解决办法:使用$set方法

修改数据的长度:

this.selectArray.length = 0

解决方法:使用空数组来替换:this.selectArray = []

2.使用v-for遍历对象

使用别名

  • {{key}}-{{value}}
  • 不使用别名,使用$key

  • {{$key}}-{{value}}
  • 注意:es5无法检测到对象增加新属性,所以vue提供了三个方法来监视对象属性:

    • $add(key,value)
    • $set(key,value)
    • $delete(key)

    自定义指令

    Vue.directive('directiveName',{
        // 这里就是指令对象的内部
        // 可以使用this来获取有用的参数
        bind: () => {
            //  准备工作:添加事件处理器等
            dom.addEventListener........
        },
        update: (oldVal,newVal) => {
            // 值更新的时候的工作
            //  初始化的时候也会被调用
        },
        unbind: () => {
            // 清理工作,比如接触bind添加的事件处理器
        }
    })

    Vue.directive('directiveName',(value) => {
        // 代替update函数
    })
    // 使用指令
    

    在指令对象中,可以只用this来获取一些有用的参数:

    • this.el: 指令绑定的元素
    • this.vm:指令的上下文viewModel
    • this.expression: 指令的表达式
    • this.arg:指令的参数
    • this.name: 指令的名字
    • this.modifiers:一个对象,指令的修饰符
    • this.descriptor: 一个对象,指令的解析结果

    vue自定义指令动态参数

    通过自定义指令中的修饰符的key作为值,更改显示的颜色

    动态指令参数

    当参数是动态的时候。

    main.js

    //当参数的值是动态的时候
    Vue.directive('color2', {
      bind: function(el, binding) {
        el.style.color = binding.value;
      }
    })
    Vue.directive('color3', {
      bind: function(el, binding) {
        el.style.color = binding.arg;
      }
    })
    

    template.vue中

    
    
    
    

    参数是静态的,将key的值作为value,改变颜色

    main.js

    Vue.directive('color', {
      bind: function(el, binding) {
        const color = Object.keys(binding.modifiers)[0]; //将key的值作为value,改变颜色,Object.keys获取key的值;
        el.style.color = color;
      }
    })
    

    template.vue中

    
    
    
    

    以上的方法,最终实现效果是一样的。

    vue中的for循环以及自定义指令解读_第1张图片

    好了,这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    你可能感兴趣的:(vue中的for循环以及自定义指令解读)