Javascript 用AJAX初始化Vue数据

Javascript 用AJAX初始化Vue数据,javascript,jquery,ajax,asp.net-mvc,vue.js,Javascript,Jquery,Ajax,Asp.net Mvc,Vue.js,我试图用AJAX查询的JsonResult中的数据填充Vue。当我从视图模型中对数据进行编码时,我的Vue可以很好地接收数据,但当我尝试使用AJAX检索数据时,Vue接收不到数据。我的代码是这样的: <script type="text/javascript"> var allItems;// = @Html.Raw(Json.Encode(Model)); $.ajax({ url: '@Url.Action("GetIt

我试图用AJAX查询的
JsonResult
中的数据填充Vue。当我从视图模型中对数据进行编码时,我的Vue可以很好地接收数据,但当我尝试使用AJAX检索数据时,Vue接收不到数据。我的代码是这样的:

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

变量allItems;//=@Html.Raw(Json.Encode(Model));
$.ajax({
url:'@url.Action(“GetItems”,“Settings”),
方法:“GET”,
成功:功能(数据){
allItems=数据;
//警报(JSON.stringify(数据));
},
错误:函数(错误){
警报(JSON.stringify(错误));
}
});
var ItemsVue=新的Vue({
el:“#项目列表”,
数据:{
项目:allItems
},
方法:{
},
就绪:函数(){
}
});
项目
年
{{Item.DisplayName}
{{Item.Year}

这是与所有适当的包括。我知道
@Url.Action(“GetItems”,“Settings”)
返回正确的Url,数据按预期返回(由success函数中的警报测试(请参阅AJAX中success函数中的注释)。按如下方式填充:
var allItems=@Html.Raw(Json.Encode(Model))
有效,但AJAX查询无效。我做错了什么吗?

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

您可以在装入的函数中进行AJAX调用(Vuejs 1.x中的“就绪”


var ItemsVue=新的Vue({
el:“#项目列表”,
数据:{
项目:[]
},
挂载:函数(){
var self=这个;
$.ajax({
url:“/items”,
方法:“GET”,
成功:功能(数据){
self.items=JSON.parse(数据);
},
错误:函数(错误){
console.log(错误);
}
});
}
});
项目
年
{{item.DisplayName}
{{item.Year}

我也有同样的问题,上面塞缪尔·德·贝克尔的回答解决了这个问题

问题在于ajax成功回调函数

如果使用this.data,则是不正确的,因为当“this”引用vue应用程序时,您可以使用this.data,但在这里(ajax成功回调函数),它不引用vue应用程序,而是“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 () {}

您必须在收到数据后更新视图的数据项,所以您只能在
success
回调函数中拥有数据!我怎么做?我不能做ItemsVue.data.Items,对吗?我不知道在那一点上如何更新它…我想我可以在
success
回调函数中创建我的Vue!抱歉,我不知道Vue.js的API,所以无法帮助。快速查看参考资料后e我建议尝试:
ItemsVue.$data.items=data
success
回调中。如果您在
success
callbackSee中创建var,您只需首先在全局范围内定义它,我尝试了这个。可能是我做错了什么,我不确定。这不应该是
self.data.items=data
?setting“self”作为对原始“this”的引用作用域是我使用vuejs 2.0的关键所在。它与var self=this一起工作;感谢-@samuelupvoted!这里有一个简单的问题,假设您有一个设置为a的本地字段视图,在加载ajax数据后,它应该说B,您是在加载数据之前还是在加载数据之后将a更改为B?这里的区别在于,如果您在加载数据之前将a设置为B加载后,视图会立即更改,但数据可能会在加载后呈现,也可能不会呈现,但如果在加载后将A更改为B,则UI会挂起一秒钟左右,直到数据恢复here@muttley91尽管这种方法可行,但并不意味着它是正确的,当然这不应该是被接受的答案。谢谢你提出这个问题。向上投票,因为有只有在完成一组数据调用并处理完所有数据后才渲染vue更有意义的情况。
 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 () {}