Enhancing Vue.js functionality with extra information stored in local storage

I've created a To Do List app where you can add tasks using a button. Each new task is added to the list with a checkbox and delete button in front of it. I'm trying to save all the values from the inputs and the checked checkboxes on the page once it's refreshed using the browser. Currently, I have implemented the use of mounted and watch functions, but it only stores the input values and not the checked checkboxes. Can someone help me fix this issue? Below is my code:

Vue.createApp({
    data(){
        return{
          placeholder: 'Start typing',
          inputvalue: '',
          notes: [],
          checked: []
        }
    },
    mounted() {
  try {
    this.notes = JSON.parse(localStorage.getItem('note'))
  } catch(e) {
    this.notes = []
  }
},
      watch: {
            notes: {
                handler: function() {
                    localStorage.setItem('note', JSON.stringify(this.notes));
                },
                deep: true
            }
        },
    methods: {
        addnewtask(){
            if (this.inputvalue !== ''){
                this.notes.push(this.inputvalue)
                this.inputvalue=''
            }
        },
        removetask(index){
            if (confirm('Do you really want to delete?'))
            this.notes.splice(index, 1)
        }
    }
}).mount(app)
body {
    font-family: sans-serif;
    font-size: 14px;
    color: #030303;
    background: #3d5f82;
}
h1 {
    font-weight: 500;
    text-transform: uppercase;
    text-align: center;
    font-style: solid;
}
.btn {
    color: #31d78c;
    place-content: center;
    place-items: center;
    width: fit-content;
    border-radius: 99px;
    border: 1px solid #31d78c;
    text-decoration: none;
    text-transform: uppercase;
    margin-right: 10px;
    margin-top: 10px;
    padding: 10px;
    font-weight: 700;
    background: #fff;
}
.btn:hover {
    cursor: pointer;
    background-color:rgb(231, 239, 235);
}
.btn.danger {
    color: #eb3c15;
    place-content: center;
    place-items: center;
    width: fit-content;
    border-radius: 99px;
    border: 1px solid #eb3c15;
    text-decoration: none;
    text-transform: uppercase;
    margin-right: 10px;
    margin-top: 10px;
    padding: 10px;
    font-weight: 700;
    background: #fff;
}
.btn.danger:hover {
    cursor: pointer;
    background-color:rgb(236, 219, 219);
}
.container {
    margin: 0 auto;
    max-width: 1000px;
}
.form-control {
    position: relative;
    margin-bottom: 10px;
}
.form-control input,
.form-control select {
    margin: 0;
    outline: none;
    border: 2px solid #ccc;
    display: block;
    width: 95%;
    color: #2c3e50;
    padding: 0.5rem 1.5rem;
    border-radius: 3px;
    font-size: 1rem;
}
.card {
    overflow: hidden;
    padding: 1rem;
    margin-bottom: 1rem;
    border-radius: 10px;
    box-shadow: 2px 3px 10px rgba(0, 0, 0, 0.2);
    background: #fff;
}
.card.center {
    display: flex;
    flex-direction: column;
    align-items: center;
}
.list {
    margin: 0;
    padding: 0;
    list-style: none;
}
.list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.5rem 0;
    transition: .22s all;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To Do List</title>
</head>
<link rel="stylesheet" href="style.css">
<style>
    [v-cloak] {
        display:none;
    }
</style>
<body>
    <div class="container" id="app" v-cloak>
      <div class="card">
          <h1>To Do List</h1>
          <div class="form-control">
             <input
                 type="text" 
                 v-bind:placeholder="placeholder" 
                 v-model="inputvalue"
                 v-on:keypress.enter="addnewtask"
              />
              <button class="btn" v-on:click="addnewtask">Add Task</button>
            </div>
            <hr />
            <ul class="list" v-if="notes.length !== 0"...>
                <li class="list-item" v-for="(note, index) in notes" v-bind:key="note">
                    <div>
                        <input type="checkbox" v-model="checked[note]"/>
                        <span :style="checked[note] ? 'text-decoration: line-through' : ''">
                            {{index+1}}) {{note}}
                        </span>
                    </div>
                    <button class="btn danger" v-on:click="removetask(index)">Delete</button>
                </li>
                <hr />
                <li>
                    <strong>Total: {{notes.length}}</strong>
                </li>
            </ul>
            <div v-else>No task exist, please add first one.</div>
      </div>
    </div>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="Vue3.js"></script>
</body>
</html>

Answer №1

My suggestion would be to integrate the checkbox value into your items array rather than keeping track of selected items separately. Here's an example of how you could structure this array:

[
  {
    title: "Title",
    selected: true
  }
]

You can then use the item.selected property within your checkbox to indicate whether it is selected or not.

Additionally, instead of manually storing data in localStorage, I recommend utilizing Vuex with localStorage (https://medium.com/js-dojo/how-to-permanently-save-data-with-vuex-localstorage-in-your-vue-app-f1d5c140db69)

You can configure it so that your Vuex state is automatically saved in localStorage, allowing it to be reloaded back into your state upon page refresh. I hope this information proves helpful!

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

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

Creating a duplicate or copy of an element in jQuery using

My dilemma involves a div that consists of text/images and a custom jQuery plugin designed for those images. The plugin simply executes a fadeIn/fadeOut effect every 3 seconds using setInterval. This particular div acts as a "cache" div. When a user wants ...

Adding Typescript to a Nativescript-Vue project: A step-by-step guide

Struggling over the past couple of days to configure Typescript in a basic template-generated Nativescript-Vue project has been quite the challenge. Here's my journey: Initiated the project using this command: ERROR in Entry module not found: Erro ...

Switch between the table data elements in an .hta document

The response provided by Dr.Molle in a previous post here was accurate, but it only functioned with <div>. I am required to utilize <table>. Though I found a script that works flawlessly outside of my VBScript, it does not work when embedded in ...

Receiving a 404 error when attempting to use the 'import' statement within a script tag labeled as a module

I am currently working on a NodeJS project that utilizes Webpack for bundling and Express for serving. Whenever a user visits the root domain, they are served an index.html file containing a <script> block in the footer with a type of module. index. ...

Challenges encountered when using random values in Tailwind CSS with React

Having trouble creating a react component that changes the width based on a parameter. I can't figure out why it's not working. function Bar() { const p =80 const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]` console.log(styl ...

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

Ways to locate two div class elements that are generated dynamically

I am looking to dynamically create 2 divs in different locations. One for displaying information and another for editing information. I want to be able to delete both divs with the same class when using the delete button. Since they are located in differe ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

What is the best way to calculate the duration of a .wav file stored locally using JavaScript?

Can you help me figure out how to determine the duration (in milliseconds) of a .wav file using JavaScript for a GreaseMonkey Script? The main challenges I'm encountering are: 1) Accessing local files 2) Retrieving the length of the wav file ...

What is the accurate way to write the ID selector for the select-option-selected in JQuery?

When it comes to extracting a value from a Select-Option using jQuery, the following syntax can be used. I have successfully retrieved data using this method. $( "#Vienna\\.rail0\\.track option:selected" ).text() However, there is an ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Utilize node.js on your local machine and leverage gulp to monitor any modifications

I recently copied a repository from https://github.com/willianjusten/bootstrap-boilerplate and followed these steps. git clone git://github.com/willianjusten/bootstrap-boilerplate.git new_project cd bootstrap-boilerplate npm install gulp The gulp comman ...

What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Althou ...

Enhancing features with jQuery's .animate() function

Can anyone help me figure out why the div on the right is not pushing itself away from the one on the left when I hover over it? I want it to move on mouseenter and return to its original position on mouseleave. The changing background colors are just ther ...

Is there a reason why the integration of OnsenUI with Vue using vue-onsenui and v-ons-segment is not functioning

I am experiencing an issue with OnsenUI and VUE vue-onsenui v-ons-segment. Instead of displaying a button bar in a row as expected, I am seeing standard buttons. The problematic code resides in a customized Monaca CLI project utilizing the minimal VUE tem ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

Post your artwork on Facebook's timeline

I am working on a website that allows users to create custom smartphone cases. One feature I want to implement is the ability for users to share their design on Facebook, including the actual design itself. I have the object and the canvas with the 's ...

Is it possible to utilize Vue's splice method within a forEach loop in order to delete multiple elements at

I am currently working on an image grid in array form. I am trying to implement a multi-deletion functionality. When a checkbox for each image in the grid is checked, I store the selected image's index in an array called selectedImages. Upon clickin ...