Refreshing component data in Vue Js

I recently created a 'read more' component using Vue Js, but encountered an issue where the component fails to re-render with new content when the text passed through props is changed.

Take a look at the code snippet for the component:

Vue.component('readmore', {
    template: 
            `
            <span>
                {{ part1 }}<span v-if="leia.mais">...
                    <span class="text-info ml-2" style="cursor:pointer;" v-on:click="readMore"> Read More</span>
                </span><span v-if="!leia.mais">{{ part2 }}
                    <span class="text-info ml-2" style="cursor:pointer;" v-if="leia.menos"  v-on:click="readLess">Read Less</span>
                </span>
            </span>
            `,
    data: function () {
        return {
            part1: '',
            part2: '',
            leia: {},
            defaultMaxChr: 200
        }
    },
    
    props: ['maxchr', 'text'],

    created: function () {
        var text = this.text;
        var maxchr = this.maxchr ? this.maxchr : this.defaultMaxChr;
        if ((undefined === text) || (0 === text.length)) {
            console.warn('READ MORE COMPONENT: Undefined text parameter or empty string passed.');
            return;
        }

        if (text.length <= maxchr) {
            this.part1 = text;
            this.part2 = '';

            this.leia = {mais: false, menos: false};
        } else {
            this.part1 = text.substr(0, maxchr);
            this.part2 = text.substr(maxchr);

            this.leia = {mais: true, menos: false};
        }
    },
    methods: {
        readMore: function()
        {
            this.leia.mais = false;
            this.leia.menos = true;
        },

        readLess: function()
        {
            this.leia.mais = true;
            this.leia.menos = false;
        },

    },

});

When I modify the input below, there seems to be no change in the output:

<readmore> and <input> are nested within another component, which assigns the text value in its data attribute.

<input v-model="text">

<readmore
    v-bind:text="text"
    v-bind:maxchr="100"
></readmore>

Answer №1

Your logic is located within the created function, which only runs once during the initial load of the component. This means it won't run again when the text prop changes. To monitor changes in the text prop, you should utilize watch with immediate execution.

watch: {
  text: {
    handler() {
        var text = this.text;
        var maxchr = this.maxchr ? this.maxchr : this.defaultMaxChr;
        if ((undefined === text) || (0 === text.length)) {
            console.warn('COMPONENT READ MORE: Text parameter is undefined or an empty string was passed.');
            return;
        }

        if (text.length <= maxchr) {
            this.part1 = text;
            this.part2 = '';

            this.readMore = {more: false, less: false};
        } else {
            this.part1 = text.substr(0, maxchr);
            this.part2 = text.substr(maxchr);

            this.readMore = {more: true, less: false};
        }
    },
    immediate: true
  }
}

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

What is the process for removing an element from my Reducer Object?

I'm facing a challenge with my reducer object structure. Here's an example of what it looks like: clientData : { 1080 : [{ID : 1111,name : 'John'},{ID : 2222,name : 'Stan'},], 1090 : [{ID : 3333,name : 'Adam'},{ ...

An error has occurred with JSONP due to a lack of the 'Access-Control-Allow-Origin' header in the cross-origin request

Currently, I am utilizing Ajax to retrieve data from Twitter through their API. In attempting to employ jsonp, it seems like I have everything set up correctly (or so I thought). <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery. ...

I am having issues with sendKeys and click() functions in my code. I am unable to access the elements using Protractor's javascript

<input class="form-control validation-field ng-dirty ng-touched ng-invalid" placeholder="Password" type="password"> Despite using the element to retrieve it, I am unable to send keys and no error message is displayed. This issue persists in both Fir ...

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...

In what way does Angular incorporate _page-theme.scss assets?

The Angular Material Documentation homepage includes a specific scss file: https://github.com/angular/material.angular.io/blob/master/src/app/pages/homepage/_homepage-theme.scss Although this scss file is not directly imported into the component's ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

Issue with ngFor displaying only the second item in the array

There are supposed to be two editable input fields for each section, with corresponding data. However, only the second JSON from the sample is being displayed in both sections. The JSON in the TypeScript file appears as follows: this.sample = [ { "se ...

Incrementing values in ng-repeat object automatically

My project involves extracting game information from mlb.com and utilizing angularjs along with the ng-repeat directive to display it. A sample of the JSON feed is shown below. { "data": { "games": { "next_day_date": "2017-08-19", "mo ...

How do you define a global variable with Javascript and Jquery?

I am attempting to create a global jQuery object variable in order to be able to access it from various functions. Here is my current approach: var object_list = $("#object_list"); var list_length = object_list.find("li").length; $(document).on('ke ...

Exporting a node express app for chai-http can be done by creating a module

I have set up an express app with multiple endpoints and am currently using mocha, chai, and chai-http for testing. Everything was running smoothly until I added logic for a pooled mongo connection and started creating endpoints that rely on a DB connectio ...

Exploring the power of Typescript alongside Styled Components and Material UI

Working with Typescript in conjunction with MUI and Styled-Components may lead to the need to pass props directly to MUI elements to address type errors... const Index = () => { return ( <StyledButton variant="contained" > ...

The stylesheet_pack_tag seems to be malfunctioning as it is not producing any output, despite the fact that the CSS file exists

After a Rails update, we encountered an issue with the stylesheet_pack_tag in our VueJS client application. Even though Webpacker successfully generates the CSS file in the /public/packs folder along with other files such as JS, the stylesheet_pack_tag s ...

How to troubleshoot errors in rendering a react Route component with a wrapper-component for better functionality?

I am working on a basic ReactJS app and I am trying to set up an authentication check. The idea is that if a user is authenticated, they can access certain pages, and if not, they should be redirected to the /login page. Here is my routes configuration: ex ...

Is there a different term I can use instead of 'any' when specifying an object type in Typescript?

class ResistorColor { private colors: string[] public colorValues: {grey: number, white: number} = { grey: 8, white: 9 } } We can replace 'any' with a specific type to ensure proper typing in Typescript. How do we assign correct ...

Incorporate seamless integration by using the npm install command

I am currently facing an issue where I need to identify and remove unused dependencies from my package.json file every time I run npm install for my app. Is there a method to automatically include the npm package https://www.npmjs.com/package during the n ...

The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify. I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine exc ...

Retrieve a value for a variable through the fusion of dynamic and static text

I have multiple checkboxes with unique IDs like this: <input id="apple" /> <input id="banana" /> <input id="orange" /> In addition, I have several variables with the word 'Tree' added to the end of their IDs. While I can retri ...

Customize chrome's default shortcuts with JavaScript

I'm working on an application that requires me to override some shortcut keys in the Chrome browser. While I'm able to create custom shortcuts to trigger alerts like in this Stackblitz example, I'm having trouble overriding a few default sho ...

Issue with SharePoint back-to-top functionality: unable to apply custom class during page scrolling

I am currently working on implementing a "back to top" functionality in the SharePoint master page. The back to top feature itself is functional, however, I am encountering an issue with adding a class that will show or hide the icon based on page scroll. ...

Create three div elements that mimic the appearance and functionality of a video to the fullest extent possible

Dear all, I am currently working on a project where I aim to achieve a layout similar to the one featured in this video. The goal is to have 3 divs aligned horizontally, with an image div positioned at the center while the other two divs contain random let ...