如何使用Vue.js显示?

时间:2017-10-27 10:38:47

标签: javascript php html vue.js

{ message: "Hello how are you", status: false, state: Kerala }

以下值是AJAX请求的响应。每次响应都会发生变化。我需要使用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>

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:0)

我从$.ajax看到你将vue.js与jquery混合在一起,应该尽可能避免。您可以为AJAX请求使用不同的库,例如axios。

以下是使用带有vue.js的axios的说明: https://alligator.io/vuejs/rest-api-axios/