laravel - 更新 Vuejs 列表
问题描述
我正在使用 laravel 和 vue 我想实时更新我的数据(当新帖子/项目发布时)主页添加它(不需要刷新)
问题
- 我怎样才能做到这一点?
代码
my component
<div v-for="project in projects" :key="project.slug">
my script
<script>
import pagination from 'laravel-vue-pagination';
var moment = require('moment');
export default {
data() {
return {
projects: {},
app_name: process.env.MIX_APP_NAME,
}
},
mounted: function() {
this.load();
},
components: {
pagination
},
methods: {
//shorting projects body
readMore: function (text, length, suffix) {
return text.substring(0, length) + suffix;
},
//getting all projects
load: function(page = 1) {
Vue.use(require('vue-moment'), {
moment
});
axios.get('/api/projects?page=' + page)
.then(
response => {
this.projects = response.data.data;
// timing
Vue.filter('timeAgo', function(value){
return moment(value).fromNow();
});
//adding tooltip
Vue.nextTick(function () {
$('[data-toggle="tooltip"]').tooltip();
});
}
)
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
},
//numbers decimals
formatPrice(value) {
let val = (value/1).toFixed(0).replace('.', ',')
return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")
},
}
}
</script>
对不起下面的部分(只是为了能够发布这个问题 stackoverflow限制
..................................................... ..................................................... ..................................................... ..................................................... ...................................
解决方案
如果您希望服务器能够在有新数据时更新客户端,则需要查看 Websockets。
流程将是:添加新项目,来自服务器的 Websocket 将此新项目作为 json 发送给所有客户端,客户端将此项目添加到项目的 javascript 列表中,vue 自动更新可见列表以反映此新项目。
如果 websockets 是不可能的,那么你只需要在很短的时间内运行你的加载命令,这样它就会感觉“实时 ish”
推荐阅读
- python - 我可以在熊猫数据框中有两行标题吗?
- sql - 在 SQL 查询中传递 ID
- javascript - Knex 找不到带有 esm 模块的迁移路径
- javascript - Discord.js - 嵌入
- python - Python 目录结构问题并且在一台机器上有多个版本
- flutter - 在 CustomScrollView 中显示 TabBarView
- php - Foreach 循环仅存储多维数组的第一个索引 | 拉拉维尔
- python - 即使添加到 PATH,Python 也无法工作
- python - 如何区分地理定位折线下方和上方的点?
- powershell - 在 Powershell 中合并 CSV 文件遍历子文件夹 - 归档和删除旧文件使用 Target-CSV 的文件夹名称