2017-10-27 4 views
0
{ message: "Hello how are you", status: false, state: Kerala } 

以下の値は、AJAXリクエストの応答です。応答が変わるたびに。私はVue.jsを使ってそれを印刷する必要がありますか?Vue.jsを使ってこれを表示するには?

<script> 
regBox = new Vue({ 
    el: "#regBox", 
    data: { 
     username : '', 
    }, 
    methods: { 
     handelSubmit: function(e) { 
      data = {}; 
      data['username'] = this.username; 
      $.ajax({ 
       url: 'https://herokuapp.com/api/user/box/', 
       data: data, 
       type: "POST", 
       dataType: 'json', 
       success: function(e) { 
        if (e.status) { 
         alert(" Success") 
        } else { 
         alert("failed"); 
        } 
       } 
      }); 
      return false; 
     } 
    }, 
}); 
</script> 
+0

たぶん、この問題のコメントデモが参考になります。https://stackoverflow.com/questions/46927074/what-c​​auses-vuejs-このインスタンスではdom-in-this-instanceを更新する – WaldemarIce

+0

私は同じアイデアを得ていませんでした – Wanderer

答えて

0

例1:ただ一つの応答時間で

regBox = new Vue({ 
el: "#regBox", 
data: { 
    username : '', 
    response: { 
     message: '', 
     status: '', 
     state: '' 
    } 
}, 
methods: { 
    handelSubmit: function(e) { 
     var vm = this; // so you can access "this" inside jquery success 
     data = {}; 
     data['username'] = this.username; 
     $.ajax({ 
      url: 'https://herokuapp.com/api/user/box/', 
      data: data, 
      type: "POST", 
      dataType: 'json', 
      success: function(e) { 
       vm.response = e; 
      } 
     }); 
     return false; 
    } 
}, 
}); 

例テンプレート:

<div id="regBox"> 
    <div v-if="response.message" class="{ 'alert-success': response.status, 'alert-danger': !response.status}"> 
     <p>{{ response.message }}</p> 
    </div> 
</div> 

例2:時間で複数の応答:

regBox = new Vue({ 
el: "#regBox", 
data: { 
    username : '', 
    responses: [] 
}, 
methods: { 
    handelSubmit: function(e) { 
     data = {}; 
     data['username'] = this.username; 
     $.ajax({ 
      url: 'https://herokuapp.com/api/user/box/', 
      data: data, 
      type: "POST", 
      dataType: 'json', 
      success: function(e) { 

       // like this to prevent all items to be binded, they would otherwise change whenever you get a new response. 
       vm.responses.push({ 
        message: e.message, 
        status: e.status, 
        state: e.state 
       }); 
      } 
     }); 
     return false; 
    } 
}, 
}); 

テンプレート例:その後

<div id="regBox"> 
    <div class="{ 'alert-success': response.status, 'alert-danger': !response.status}" v-for="response in responses"> 
     <p>{{ response.message }}</p> 
    </div> 
</div> 

あなたはいくつかの時間後に応答を削除したい場合、あなたはまた、setTimeoutを使用することができます。

+0

フロントエンドに表示する方法も? – Wanderer

+0

ちょっと@ワンダラー私はテンプレートで私の答えを更新しましたが、これは単なる例です。 vueJsでデータを表示する方法がわからない場合は、最初にチュートリアルを行うことをお勧めします。 (https://laracasts.com/series/learn-vue-2-step-by-step) – Andy

0

$.ajaxから、vue.jsとjqueryが混在していることがわかります。できるだけ避けるべきです。 Axisなど、AJAXリクエストには別のライブラリを使用できます。ここで

はvue.jsでaxiosを使用するための説明です: https://alligator.io/vuejs/rest-api-axios/

関連する問題