gpt4 book ai didi

javascript - Vue循环列表-将ajax返回的数据附加到列表中?

转载 作者:行者123 更新时间:2023-12-03 02:49:03 24 4
gpt4 key购买 nike

如何在 ajax 调用后附加 vue 列表?

这是我使用 Vue 的 HTML:

     <a href="#" id="button-load" class="button button-load" data-posts-endpoint="...">Load More</a>

<div id="news-posts">

<!-- item -->
<template v-for="item in items">
<div class="cell large-4 medium-6">

<!-- image has no padding -->
<div class="card grid-item">
<div class="card-divider">
<h4 class="heading heading-card"><a :href=item.url><span v-html=item.title></span></a></h4>
</div>
<div class="card-date">
<span v-html=item.date></span>
</div>
<div class="card-section"><p v-html=item.excerpt></p></div>
<div class="text-right">
<a :href=item.url class="button button-more"><i class="material-icons">chevron_right</i></a>
</div>
</div>

</div>
<!-- item -->
</template>
<!-- vue - loop -->

</div>

Js:

  // Render template with Vue.
// Get json of catering menu.
var element = document.getElementById('news-posts')
var buttonLoad = document.getElementById('button-load')
if (element !== null) {
// var endpoint = $('#button-load').data('posts-endpoint') // jQuery
var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS
var getData = await axios.get(endpoint)
var cateringMenu = new Vue({
el: '#news-posts',
data: {
items: getData.data
}
})
}

$("#button-load").click(function(){
var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS
$.get(endpoint, function(data, status){
var cateringMenu = new Vue({
el: '#news-posts',
data: {
items: data
}
})
})
return false
})

当然,它不会将ajax返回的数据追加到列表中。

有什么想法吗?

编辑:

可以使用:

  methods: {
fetch: function (event) {
var self = this
// `this` inside methods points to the Vue instance
$.ajax({
url: endpoint,
method: 'GET',
success: function (data) {
data.map(function(item) {
self.items.push(item)
})
},
error: function (error) {
console.log(error)
}
})
}
}

最佳答案

您是否尝试过让您的按钮执行 Vue 中定义的方法,以便您可以访问实例并可以使用 this 设置项目,如下所示;

methods: {
fetch: function(){
var endpoint = buttonLoad.getAttribute('data-posts-endpoint');
$.get(endpoint, function(data, status){
this.items = data; //set items.
})
}
}

然后将 fecth 方法添加到您的按钮中(需要位于 vue 包装器中,目前看起来位于外部)v-on:click.prevent="this.fecth"

关于javascript - Vue循环列表-将ajax返回的数据附加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com