首页 > 解决方案 > 更新 Vuejs 列表

问题描述

我正在使用 laravel 和 vue 我想实时更新我的​​数据(当新帖子/项目发布时)主页添加它(不需要刷新)

问题

  1. 我怎样才能做到这一点?

代码

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

..................................................... ..................................................... ..................................................... ..................................................... ...................................

标签: laravelvue.js

解决方案


如果您希望服务器能够在有新数据时更新客户端,则需要查看 Websockets。

流程将是:添加新项目,来自服务器的 Websocket 将此新项目作为 json 发送给所有客户端,客户端将此项目添加到项目的 javascript 列表中,vue 自动更新可见列表以反映此新项目。

如果 websockets 是不可能的,那么你只需要在很短的时间内运行你的加载命令,这样它就会感觉“实时 ish”


推荐阅读