【问题标题】:Initializing Vue data with AJAX使用 AJAX 初始化 Vue 数据
【发布时间】:2015-12-01 13:08:43
【问题描述】:

我正在尝试使用来自 AJAX 查询的 JsonResult 的数据填充 Vue。当我从我的视图模型对数据进行编码时,我的 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查询没有。我做错了吗?

【问题讨论】:

  • 您必须在收到数据后更新视图的数据项。请注意,该 ajax 是异步的(因此得名),因此您只会在 success 回调函数中拥有数据!
  • 我该怎么做?我不能做 ItemsVue.data.Items 对吗?我不确定当时如何更新它......
  • 我想我可以在success回调函数中创建我的Vue!
  • 对不起,我不知道vue.js的API,所以帮不上忙。在快速查看参考后,我建议尝试:ItemsVue.$data.items=data inside success 回调。
  • 如果你在successcallback 中创建它,你只需要先在全局范围内定义它

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


【解决方案1】:

您可以在挂载的函数内部进行 ajax 调用(在 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 = JSON.parse(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>

【讨论】:

  • 看,我试过了。也许我做错了什么,我不确定。
  • 不应该是self.data.Items = data 吗?
  • 设置“self”作为对原始“this”范围的引用是关键
  • 我正在使用已安装的 vuejs 2.0。它与 var self = this 一起工作;谢谢 - @samuel
  • 点赞!这是一个简单的问题,假设您有一个设置为 A 的本地字段视图,加载 ajax 数据后应该说 B,您应该在加载之前还是加载数据之后将 A 更改为 B?此处的区别在于,如果您在加载之前将 A 设置为 B,则视图会立即更改,但加载后数据可能会或可能不会呈现,但如果您在加载后将 A 更改为 B,则 UI 会挂起一秒钟左右,直到数据在这里跨度>
【解决方案2】:

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

【讨论】:

  • @muttley91 尽管这种方式可行,但这并不意味着它是正确的,当然这不应该是公认的答案。感谢您发布问题。
  • 投了赞成票,因为在某些情况下,只有在一组数据调用完成并且所有数据都已处理后才渲染 vue 更有意义。
【解决方案3】:

我有同样的问题,上面 Samuel De Backer 的回答解决了。

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

如果你使用this.data是错误的,因为'this'引用vue-app时,你可以使用this.data,但是这里(ajax成功回调函数),this没有引用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 () {}

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 2016-01-10
    • 2015-09-22
    • 2018-07-14
    • 1970-01-01
    • 2021-02-21
    • 2019-04-09
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多