2015-10-06 33 views
0

我有一個有三個按鈕的表單,每個按鈕的值分別爲1,2和3。它們被放置在一個表單中,並且用戶要單擊導致表單更改的三個中的一個。我試圖根據用戶按下的按鈕的值進行ajax調用。我試圖這樣,像這樣:使用Vue.js獲取按鈕的值

<form method="POST"> 
    <input type="hidden" name="_token" id="token" value="{{ csrf_token() }}"> 

    <div class="col-md-4 col-sm-6 feature text-center"> 
     <div class="content"> 
     <button class="btn btn-default btn-question" 
     v-model="selectedcategory" 
     v-on="click: search" 
     value="1">Category 1 
     </button> 
     </div> 
    </div> 

    <div class="col-md-4 col-sm-6 feature text-center"> 
     <div class="feature-content"> 
     <button class="btn btn-default btn-question" 
     v-model="selectedcategory" 
     v-on="click: search" 
     value="2">Category 2 
     </button> 
     </div> 
    </div> 

    <div class="col-md-4 col-sm-6 feature text-center"> 
     <div class="feature-content"> 
     <button class="btn btn-default btn-question" 
     v-model="selectedcategory" 
     v-on="click: search" 
     value="3">Category 3 
     </button> 
     </div> 
    </div> 
</form> 

我的JS看起來像這樣

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value'); 

new Vue({ 
    el: '#picker', 

    data: { 
     selectedcategory: '0' 
    }, 

    methods:{ 

     search: function(e){ 
      e.preventDefault(); 

      var getresults = this.$http.get('api/products/' + this.selectedcategory, function(products){ 
       this.$set('products', products); //key, data 
      }); 
     } 
    } 
}); 

這樣,我無法獲得按鈕的價值,但如果我做一個簡單的選擇下拉菜單像這樣

<select v-model="selectedcategory" v-on="click: 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

然後ajax調用成功。

我怎樣才能達到這個結果,但用按鈕呢?

回答

1

你可以試試下面的

<form method="POST"> 
    <input type="hidden" name="_token" id="token" value="{{ csrf_token() }}"> 

    <div class="col-md-4 col-sm-6 feature text-center"> 
     <div class="content"> 
     <button class="btn btn-default btn-question" 
     v-on="click: search(1, $event)">Category 1 
     </button> 
     </div> 
    </div> 

    <div class="col-md-4 col-sm-6 feature text-center"> 
     <div class="feature-content"> 
     <button class="btn btn-default btn-question" 
     v-on="click: search(2, $event)">Category 2 
     </button> 
     </div> 
    </div> 

    <div class="col-md-4 col-sm-6 feature text-center"> 
     <div class="feature-content"> 
     <button class="btn btn-default btn-question" 
     v-on="click: search(3, $event)">Category 3 
     </button> 
     </div> 
    </div> 
</form> 

而在你的JS文件

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value'); 

new Vue({ 
    el: '#picker', 

    methods:{ 

     search: function(id, e){ 
      e.preventDefault(); 

      var getresults = this.$http.get('api/products/' + id, function(products){ 
       this.$set('products', products); 
      }); 
     } 
    } 
});