使用AJAX初始化Vue数据 [英] Initializing Vue data with AJAX

查看:87
本文介绍了使用AJAX初始化Vue数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自AJAX查询的 JsonResult 的数据填充Vue。当我从View Model中编码时,我的Vue接收数据就好了,但是当我尝试使用AJAX检索它时却没有。这是我的代码的样子:

I'm trying to populate a Vue with data from the JsonResult of an AJAX query. My Vue receives the data just fine when I encode it from my View Model, but not when I try to retrieve it using AJAX. Here's what my code looks like:

<script type="text/javascript">

        var allItems;// = @Html.Raw(Json.Encode(Model));

        $.ajax({
            url: '@Url.Action("GetItems", "Settings")',
            method: 'GET',
            success: function (data) {
                allItems = data;
                //alert(JSON.stringify(data));
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });

        var ItemsVue = new Vue({
            el: '#Itemlist',
            data: {
                Items: allItems
            },
            methods: {

            },
            ready: function () {

            }
        });
</script>

<div id="Itemlist">
    <table class="table">
        <tr>
            <th>Item</th>
            <th>Year</th>
            <th></th>
        </tr>
        <tr v-repeat="Item: Items">
            <td>{{Item.DisplayName}}</td>
            <td>{{Item.Year}}</td>
            <td></td>
        </tr>
    </table>
</div>

这是所有适当的包含。我知道 @ Url.Action(GetItems,Settings)返回正确的URL,数据按预期返回(由成功函数中的警报测试) (请参阅AJAX中的成功函数中的注释)。像这样填充它: var allItems = @ Html.Raw(Json.Encode(Model)); 有效,但是AJAX查询我做错了什么?

This is with all of the proper includes. I know that @Url.Action("GetItems", "Settings") returns the correct URL and the data comes back as expected (as tested by an alert in the success function (see comment in success function in AJAX). Populating it like so: var allItems = @Html.Raw(Json.Encode(Model)); works, but the AJAX query does not. Am I doing something wrong?

推荐答案

你可以在挂载函数内部进行ajax调用(readyin Vuejs 1.x)。

You can make the ajax call inside of the mounted function ("ready" in Vuejs 1.x).

<script type="text/javascript">
var ItemsVue = new Vue({
    el: '#Itemlist',
    data: {
        items: []
    },
    mounted: function () {
        var self = this;
        $.ajax({
            url: '/items',
            method: 'GET',
            success: function (data) {
                self.items = data;
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
});
</script>

<div id="Itemlist">
    <table class="table">
        <tr>
            <th>Item</th>
            <th>Year</th>
        </tr>
        <tr v-for="item in items">
            <td>{{item.DisplayName}}</td>
            <td>{{item.Year}}</td>
        </tr>
    </table>
</div>

这篇关于使用AJAX初始化Vue数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆