Displaying content conditionally in Vue JS upon the initial page load

I am currently working on a Vue component that is supposed to render the first time a page is opened. However, I am facing some confusion regarding the logic behind this. My approach involves using localStorage to check for an item called 'wasVisited'. I need to set it to 1 at a certain point so that the modal does not appear the next time the view triggering the modal is accessed. I am just unsure of where exactly I should place this logic; the mounted() function doesn't seem like the right spot.

<template v-if="localStorage.getItem('wasVisited') === null">
<div>
    <b-modal ref="disc" title="Hello" ok-only ok-variant="light" size="lg" body-bg-variant="dark" header-bg-variant="dark" header-text-variant="light" body-text-variant="light" footer-bg-variant="dark" footer-text-variant="light" title-class="text-light">
        <div class="text-justify modal-text">
            <p>Hi from modal</p>
        </div>
    </b-modal>
</div>
</template>

<script>
export default {
    methods: {
        showModal() {
            this.$refs['disc'].show()
        },
        hideModal() {
            this.$refs['disc'].hide()
        },
    },

    mounted() {
        console.log('Modal mounted.');
        this.showModal();
        localStorage.setItem('wasVisited', '1');
    }
}
</script>


Answer №1

A more efficient way to structure your code would be:

<template>
<div>
    <b-modal ref="disc" title="Hello" ok-only ok-variant="light" size="lg" body-bg-variant="dark" header-bg-variant="dark" header-text-variant="light" body-text-variant="light" footer-bg-variant="dark" footer-text-variant="light" title-class="text-light">
        <div class="text-justify modal-text">
            <p>Hi from the modal</p>
        </div>
    </b-modal>
</div>
</template>

<script>
export default {
    methods: {
        showModal() {
            this.$refs['disc'].show()
        },
        hideModal() {
            this.$refs['disc'].hide()
        },
    },

    mounted() {
        console.log('Modal has been mounted.');
        if(localStorage.getItem('wasVisited') === null) this.showModal();
        localStorage.setItem('wasVisited', '1');
    }
}
</script>

In this updated version, I have eliminated the v-if in your template and instead integrated it into the mounted property. This means that if the localStorage value hasn't been set, the function to show the modal will automatically be triggered. Additionally, we set a value for wasVisited.

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

Creating a nested array of objects using a recursive function

How can I utilize my getChildren() function to create a larger function that takes my two main arrays objs and objRefs, and generates a single array of objs showcasing their parent/child relationship? Below are the two primary data arrays: const objs = [ ...

Can you explain how the interactive notification on stackoverflow is generated when you are responding to a question and someone posts a new answer?

Have you ever been in a situation where you're writing an answer to a question, but then someone else posts their response and a popup appears notifying you of the new answer? I'm curious about how that whole process works. It seems like the answ ...

Navigation bar in reactjs remains visible even after clicking on an icon button, causing a temporary issue with

I'm facing an issue with my navigation bar created using material-ui. I have an onClick function set up so that when the user clicks the icon button, the navigation redirects to a new page and then should close. However, no matter what I try, the navi ...

What is the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

Arranging elements using the ng-repeat directive in AngularJS

My question pertains to an array I am working with: $scope.answers=["","","",""] This array contains several empty elements. <li ng-repeat="item in answers "><input type="text" ng-model="item"/></li> When running this code, an error i ...

What is the best way to accomplish a smooth transition of background colors similar to this design

I was browsing different websites and stumbled upon this amazing background color transition that caught my attention. I really liked it and now I want to create something similar on my own website. Despite my best efforts, I haven't been able to achi ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

What happens if you try to add a member to a Mailchimp list who is already on the list

After following Angela Yu's course for the past few weeks, I attempted to implement the Mailchimp API as she demonstrates. However, I encountered difficulties due to recent changes in Mailchimp. Despite this setback, I was able to find the API referen ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Creating a resizable SVG rectangle element with React

Hey, I'm a beginner in Svg and currently learning ReactJs. I have a question that I'm not sure is possible or not. I have an Svg element with its children wrapped inside a g. The g element contains a rect element that I want to make resizable usi ...

Modify a single field in user information using MySQL and NodeJS

I am currently working on developing a traditional CRUD (create, read, update, delete) API using NodeJS/Express and MySQL. One of the routes I have created is responsible for updating user information, which is functioning correctly. The issue: When I d ...

How can Vue.js implement a satisfactory method for synchronizing computed values with asynchronous data?

Imagine retrieving a list of products from the state manager in your Vue.js component, where a computed property is then used to process this list for display on the DOM. <template> <span>{{ computedProducts }}</span> </template> ...

Retrieving chosen row data in Angular 6 Material Table

I am attempting to send the value of a selected row from one component to another upon clicking a button. However, in this particular example, I'm unsure where to obtain the selected row values and how to pass them on button click. After that, routing ...

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

Exploring Angular 2: Unveiling the secrets of lifecycle hooks in lazy loaded

Currently, I'm working on an application that involves lazy loaded Angular modules. I have a straightforward inquiry: Is there a way to detect an event once a module is loaded? For instance, similar to the OnInit lifecycle hook for components. I fo ...

Next.js encounters an error when importing web3

Currently, I am utilizing next js and material ui to create a demo dapp for educational purposes. With metamask installed, I have successfully implemented a "connect to wallet" button. My issue arises when attempting to import the Web3 constructor. This i ...

The Material UI appbar fails to resize properly on mobile devices

I have added a material-ui appbar to the top of my website. Check it out here: Website Appbar However, when I resize the website to mobile size, the appbar does not adjust responsively to the screen. Here's how it looks on mobile: Appbar when in mobi ...

Unlock the power of Vue 2: harnessing computed properties in your methods

I am trying to iterate through an array that contains objects and extract a list of author names from these objects. In order to achieve this, I intend to create a method that I will use with forEach(). However, I am facing an issue where I cannot access ...

What is the scope parameter for the facebook-node-sdk in node.js?

https://github.com/amachang/facebook-node-sdk I decided to utilize this module in order to create a Facebook-integrated login for my node.js project, following the example provided with express: var express = require('express'); var Facebook = ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...