2017-06-16 5 views
1

私はVue.js noobで、クリックされたリンクの親のforループの中でクラスを切り替える方法を見つけようとしています。Vue.jsの親クラスを更新する

「高度な」リンクをクリックして、そのセクションのsection.advanced-fields要素のオーバーレイクラスを切り替えたいとします。私は各セクションにonOffデータ属性を追加することができますが、私はデータベースに保存して、不要なデータフィールドを追加したくないことを知っています。

誰でも正しい方向に向けることができます。ありがとう。

ここに私のコードの簡略版があります。

<div id="app"> 
    <section v-bind:class="{ overlay: onOff }" v-for="section in sections"> 
     <a href="#0" @click.prevent="showAdvanced(section)">Advanced</a> 

     <div class="advanced-fields" v-bind:class="{ overlay: onOff }" v-show="onOff"> 
      <fieldset> 
       <label> 
        ID 
        <input type="text" name="section[id]"> 
       </label> 
      </fieldset> 
      <fieldset> 
       <label> 
        Class 
        <input type="text" name="section[css_class]"> 
       </label> 
      </fieldset> 
     </div> 
    </section> 
</div> 

<script> 
new Vue({ 
    el: "#app", 
    data:{ 
     "sections": [ 
      { 
       "id": "section-1", 
       "css_class": "" 
      }, 
      { 
       "id": "section-2", 
       "css_class": '' 
      } 
     ], 
     "onOff": false 
    }, 
    methods: { 
     showAdvanced: function(section) { 
      this.onOff = !this.onOff; 
     } 
    } 
}); 
</script> 
+1

ほぼ正確に同じ質問と答え:私はそれを把握する助けhttps://stackoverflow.com/a/44598666/7636961 – wostex

+1

ありがとう@wostex、私は他のケースの誰に以下の私の更新されたコードを投稿しますこれに遭遇する。 – ferne97

答えて

0

この回答はVue bind click that adds active class (and removes from the last one)です。ここで

https://jsfiddle.net/ferne97/n1hfde94/

正しく動作する更新されたコードです。

<div id="app"> 
    <section v-bind:class="{ overlay: index == isActive }" v-for="(section, index) in sections"> 
     <a href="#0" @click.prevent="showAdvanced(index)">Advanced</a> 

     <div class="advanced-fields" v-bind:class="{ overlay: index == isActive }" v-show="index == isActive"> 
      <fieldset> 
       <label> 
        ID 
        <input type="text" name="section[id]" v-model="section.id"> 
       </label> 
      </fieldset> 
      <fieldset> 
       <label> 
        Class 
        <input type="text" name="section[css_class]" v-model="section.css_class"> 
       </label> 
      </fieldset> 
     </div> 
    </section> 

    <pre>{{ $data }}</pre> 
</div> 

<script> 
new Vue({ 
    el: "#app", 
    data:{ 
     "sections": [ 
      { 
       "id": "section-1", 
       "css_class": "" 
      }, 
      { 
       "id": "section-2", 
       "css_class": '' 
      } 
     ], 
     "isActive": null 
    }, 
    methods: { 
     showAdvanced: function(index) { 
      this.isActive = this.isActive === index ? null : index 
     } 
    } 
}); 
</script> 
関連する問題