Vue.js自定义指令访问循环上下文

时间:2018-11-16 16:22:53

标签: vue.js vuejs2

Vue.directive("custom", {
    inserted(el, binding, vnode) {
        let val = binding.value;
        let arg = binding.arg
        let mods = binding.modifiers
        let expr = binding.expression
        let cont = vnode.context
        .... // modify loop
    }
})

我正在尝试在vue中构建自定义指令。该指令可以在v-for循环内部或外部触发。当它在v-for循环内触发时,我需要当前迭代的上下文

v-for="item in list"  // i need the context for item

但是我对如何获得它一无所知。即使使用v-for包含索引的版本

v-for="(item, index) in list"  // i need the context for item

在指令插入函数中都不能访问这些值。至少我在任何地方都找不到它们。

对找到这些值的任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

来自https://vuejs.org/v2/guide/custom-directive.html

  

定向钩子传递了以下参数:

     

el:指令绑定到的元素。这可以用来   绑定:包含   以下属性。
...
  value:传递给指令的值。例如在   v-my-directive =“ 1 + 1”,该值为2。

您已经在这里

let val = binding.value;

您只需要将其传递给指令即可。

<div v-for="item in list" :v-custom="item"></div>

答案 1 :(得分:1)

value directive hook argument中使用binding

例如,在v-custom="item"中,value将是item

Vue.directive("custom", {
    inserted(el, binding, vnode) {
        let val = binding.value; // this value is the item
        let arg = binding.arg
        let mods = binding.modifiers
        let expr = binding.expression
        let cont = vnode.context
        .... // modify loop
    }
})

示例(请参阅日志)

Vue.directive("custom", {
  inserted(el, binding, vnode) {
    let val = binding.value;
    let arg = binding.arg
    let mods = binding.modifiers
    let expr = binding.expression
    let cont = vnode.context

    console.log(val)
  }
})

new Vue({
  el: "#app",
  data: {
    todos: [{
        text: "Learn JavaScript",
        done: false
      },
      {
        text: "Learn Vue",
        done: false
      },
      {
        text: "Play around in JSFiddle",
        done: true
      },
      {
        text: "Build something awesome",
        done: true
      }
    ]
  },
  methods: {
    toggle: function(todo) {
      todo.done = !todo.done
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="todo in todos" v-custom="todo">
      <label>
        <input type="checkbox"
          v-on:change="toggle(todo)"
          v-bind:checked="todo.done">

        <del v-if="todo.done">
          {{ todo.text }}
        </del>
        <span v-else>
          {{ todo.text }}
        </span>
      </label>
    </li>
  </ol>
</div>