使用AJAX初始化Vue数据

时间:2015-09-05 14:00:57

标签: javascript jquery ajax asp.net-mvc vue.js

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

<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查询没有。我做错了吗?

3 个答案:

答案 0 :(得分:57)

您可以在已安装的函数内部进行ajax调用(在Vuejs 1.x中为“ready”)。

<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>

答案 1 :(得分:1)

我能够通过在AJAX调用的成功处理程序中执行必要的操作来解决我的问题。您可以将整个Vue对象创建放在那里,也可以只设置所需的数据。

答案 2 :(得分:0)

我有同样的问题,由上面的塞缪尔·德·巴克(Samuel De Backer)的答案解决。

问题出在ajax成功回调函数上,

如果您使用this.data,那是不正确的,因为当'this'引用vue-app时,您可以使用this.data,但是在这里(ajax成功回调函数),它不引用vue-app,相反,“ this”是指调用此函数的人(ajax调用)。

因此,您必须在ajax之前设置var self = this,然后将其传递给回调函数(成功回调)

这是我的工作代码

 created () {
     this.initialize()
  },


 mounted () {

        this.getData()
 },


 methods: {

     getData()  {




                 var getUser_url = url + 'cfc/sw.cfc?method=getUser&returnformat=json&queryformat=struct';

                console.log(getUser_url )

            /*
                You can use a plethora of options for doing Ajax calls such as Axios, vue-resource or better yet the browser's built in fetch API in modern browsers. 
                You can also use jQuery via $.ajax() API, which simply wraps the XHR object in a simple to use method call 
                but it's not recommended to include the whole jQuery library for the sake of using one method.


                http://updates.html5rocks.com/2015/03/introduction-to-fetch
                The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. 
                It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

            */


                //   **********  must use self = this ************** 
                // this reference vue-app.  must pass it to self, then pass into callback function (success call back)
                var self = this;  


                fetch(getUser_url).then(function (response) {
                                return response.json();
                        }).then(function (result) {

                                 console.log(result);  

                                 // must use self.user,  do not use this.user, 
                                 // because here, this's scope is just the function (result).   
                                 // we need this reference to vue-app, 
                                 self.user = result;  // [{}, {}, {}]  



    }); // fetch(){}


   console.log(this.user);


  }, 



initialize () {}