2016-12-28 60 views
3

我有一個vuejs 1.x v-for循環顯示一些使用自定義指令(用於tinymce)的組件的元素。該指令在表達式可以根據根元素進行分析時起作用,但由於它在循環內部,因此我需要它以某種方式引用索引。V-for循環動態表達式中的Vuejs指令

// tinymce directive 
 
    Vue.directive('tinymce-editor',{ 
 
    twoWay: true, 
 
    bind: function() { 
 
     var self = this; 
 
     // required cause textarea not in DOM yet 
 
     $(document).on('click', '#'+self.el.id, function(){ 
 
     tinymce.init({ 
 
     menubar: false, 
 
     browser_spellcheck: true, 
 
     plugins: "link image preview wordcount table", 
 
     selector: "#" + self.el.id, 
 
     setup: function(editor) { 
 
     
 
      // init tinymce 
 
      editor.on('init', function() { 
 
       tinymce.get(self.el.id).setContent(self.value); 
 
      }); 
 
      
 
      // when typing keyup event 
 
      editor.on('keyup', function() { 
 
      // ************ 
 
      // self.expression here needs to be questions[idx].value 
 
      // not question.value 
 
      // ************ 
 
      self.vm.$set(self.expression, tinymce.get(self.el.id).getContent()); 
 
      }); 
 
     } 
 
     })}); 
 
    }, 
 
    update: function(newVal, oldVal) { 
 
     // set val and trigger event  
 
     $(this.el).val(newVal).trigger('keyup'); 
 
     } 
 
     
 
    } 
 
    
 
    })
<div class="form-group" v-show="questions.length" v-for="question in questions"> 
 
     
 
      <textarea 
 
       id="textarea-{{question.id}}" 
 
       v-tinymce-editor="question.value"   
 
      >{{question.value}}</textarea> 
 
     </div>  
 
    </div

內TinyMCE的初始化,KeyUp事件得到self.expression但它需要是動態的?從documentation從問題陣..

+1

如果你想要問題的索引,你可以做這樣的事情:'v-for =「問題,我在問題中」''其中'i'是數組中問題的索引 – sisanared

回答

1

你應該考慮以下幾點:

  1. 通過這三個參數:在綁定功能el, binding, vnode
  2. binding.value會給你傳遞的值是question.value

所以你需要做出如下改變:

Vue.directive('tinymce-editor',{ 
    twoWay: true, 
    bind: function(el, binding, vnode) { 
    var self = this; 
    // required cause textarea not in DOM yet 
    $(document).on('click', '#'+self.el.id, function(){ 
    tinymce.init({ 
     menubar: false, 
     browser_spellcheck: true, 
     plugins: "link image preview wordcount table", 
     selector: "#" + self.el.id, 
     setup: function(editor) { 

     // init tinymce 
     editor.on('init', function() { 
      tinymce.get(self.el.id).setContent(self.value); 
     }); 

     // when typing keyup event 
     editor.on('keyup', function() { 
      // ************ 
      // binding.value will be questions[idx].value 
      // ************ 
      self.vm.$set(binding.value, tinymce.get(self.el.id).getContent()); 
     }); 
     } 
    })}); 
    }, 
    ... 
    ...