Optimal method for displaying content in Vue.js in read-only mode

I am currently working on a code snippet used to display messages exchanged between two users.

 <template>
    <main>
        <form action="" method="post" @submit.prevent="sendMessage">
            <textarea name="message" id="message" cols="30" rows="10" placeholder="Message"> </textarea>
            <input type="submit" value="Send">
        </form>    
        <section v-if="messages.length">
            <div v-for="message in messages">
                    {{message.body}}
                    <hr>
            </div>    
        </section>
        <section v-else>
                No messages
        </section>
    </main>
</template>
<script>
    import ajax from './ajax';
    export default {
        data () {
            return {                  
                messages: []
            }
        },
        methods: {
            sendMessage(e){                    
            },
            getMessages(pageNum, cb){
                ajax({
                         url: `${window.location.pathname}?p=${pageNum}`,
                         method: 'get',
                         callback(res){
                             cb(JSON.parse(res)); 
                         }
                     })
            }

        },
        created(){
            var vm = this;
            vm.getMessages(1, (res) => {
                vm.messages = res.data;
                vm.loaded=true;

            });

        }
    }
</script>

Regarding the v-for="message in messages" in the code snippet, I am looking for a way to display the messages without storing them in an array after rendering. The messages are read-only and will not require any event listeners. I plan to add a "load more" button that fetches 10 messages at a time and appends them to the existing messages.

If you have any suggestions on a more efficient way to implement this functionality or how I can display the messages without keeping them in an array, I would greatly appreciate it.

Thank you.

Answer №1

Vue operates on the principle that the content of your view is determined by your model. If something is removed from your model, it will also be removed from your view. Similarly, if you want something to be visible in the view, it must be included in the model.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to access MongoDB documents using NodeJS/Express

I can't seem to figure out why I am not receiving any results from a GET call I am testing with Postman. Let's take a look at my server.js file: const express = require("express"); const mongoose = require("mongoose"); const ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

Tips for effectively separating HTML and JavaScript for a cleaner code structure

Is it necessary and worth it to decouple HTML and JavaScript? In JavaScript logic, you always have to use some HTML elements... I know that in C#, you can decouple for easier maintenance and testing scenarios. ...

Node.js Express API returns an error status with an empty array response in a RestFul manner

Currently, I am in the process of developing a RestFull API using Node.JS to validate if a specific license plate is registered in my database (which happens to be MySQL). The endpoint that I have set up for this task is as follows: http://localhost:3009/_ ...

Implementing Angular to activate the JavaScript 'click' event

I am attempting to initiate an 'onclick' event within an angular controller. <div id="galerie"> <h2>{{main.Page.title()}}</h2> <hr> <div class="row"> <div class="col-sm-4 col-xs-6" ng-repeat= ...

When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude f ...

Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

Integrate a Nuxt project into an existing Express application

Is there a way to integrate a Nuxt project as middleware for an existing Express server while preserving SSR behavior? I've successfully transitioned my Vue application to Nuxt, but the nuxt-production-server is conflicting with my pre-existing serve ...

Unlocking the Potential of Vue Class Components: Exploring Advanced Customization Options

Currently, I am working on a project using Vue 2 with Typescript. However, I am facing an issue where I cannot add options to the component. <script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import HelloW ...

Developing a two-dimensional JavaScript array using an AJAX PHP request

I've been working with a MySQL table that stores image data. My goal is to extract this image data and store it in a JavaScript array. The fields I need for the array are "image_ref" and "image_name." To achieve this, I understand that I'll nee ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...

Efficiently Extracting Data from an Array of Objects Using JQuery

What is the best method to extract information from the array below? How can I retrieve data categorized by specific categories? Is there a way to access only the key values? How do I retrieve just the data values? var main = [{ "key": "all", "dat ...

Whenever I try to import a function, I encounter the error message "no exported member."

I am facing an issue with my node/typescript application where I am attempting to import a function from another file. In order to export it, I utilized exports.coolFunc = coolFunc, and for importing, I used import {coolFunc} from '../controller/coolS ...

Retrieve the initial index from a sorted array in JavaScript using an array

'I am looking to organize an array in numerical order, but I also need to be able to track the original index of each element after sorting. Consider the initial array: ptsGP = [3,8,2,5,6,9,8,4] Below is the code I am currently using to sort the ar ...

Tips for integrating Vuex store with router for seamless accessibility

Hey there! I'm currently working on a Vue project that involves using both vue-router and vuex. In my application, after a successful login, I store the JWT token in vuex. However, I am facing challenges with the following: 1) How to dynamically show ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Error: The hook call is invalid and can only be made within the body of a function component in ReactJS

Hello everyone, I am currently facing an issue with saving the lat and lng variables in the state within a hook. When trying to do so, I encounter the following error message: "Error: Invalid hook call. Hooks can only be called inside the body of a functio ...

How can you obtain constructor parameter from JSON directly within the constructor itself?

I decided to store the fixed parameters required for creating an object in a JSON file as an array. My goal was to have the constructor of the object fetch these parameters from the file. Although reading a JSON file is efficient, I wanted to explore othe ...

Troubleshooting slow/delayed performance when using manual dataItem.set() in Kendo UI Grid

I recently implemented an editable Kendo Grid with a checkbox column to toggle a boolean value, thanks to an ingenious solution offered by OnaBai. The implementation works flawlessly! The only issue I'm facing is that there seems to be a delay in cha ...