Store vueJs data in browser's localStorage

Is there a way to save the state of my game even after a page refresh using local or session storage? I've successfully stored wins in localStorage, but I'm struggling to keep the table with "X" and "O" in the same spot after a refresh. Any suggestions?

import { ref, computed, watch, onMounted } from "vue";

const player = ref("X");
const table = ref([
  ["", "", ""],
  ["", "", ""],
  ["", "", ""],
]);

const CalculateWinner = (squares) => {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
};

const winner = computed(() => CalculateWinner(table.value.flat()));

const Move = (x, y) => {
  if (winner.value) return;

  if (table.value[x][y] !== "") return;

  table.value[x][y] = player.value;

  player.value = player.value === "X" ? "O" : "X";
};

const Reset = () => {
  table.value = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""],
  ];
  player.value = "X";
};

const history = ref([]);
watch(winner, (current, previous) => {
  if (current && !previous) {
    history.value.push(current);
    localStorage.setItem("history", JSON.stringify(history.value));
  }
});

onMounted(() => {
  history.value = JSON.parse(localStorage.getItem("history")) ?? [];
});

Answer №1

Follow the same procedure you used for saving the history:

  • Within the Move method, save the entire table to local storage with
    localStorage.setItem("table", JSON.stringify(table.value));
  • Then, in the onMounted method, retrieve the saved value from local storage using
    table.value = JSON.parse(localStorage.getItem("table"));
    Ensure to call Reset if table.value is null to avoid issues upon initial launch.

If you want to store information about the current player, you can save it as a separate variable (e.g. "player") in local storage or create a game status object to hold both the table and player details.

Enjoy working with Vue!

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

Issues with Bootstrap Modal Checkbox Functionality

Issue with Bootstrap modal checkbox functionality when the checkbox is selected The desired behavior is for the bootstrap modal popup to be triggered upon clicking the checkbox Bootstrap Version: 3.3.6 Jquery Version: 2.1.3 $(function() { $(&ap ...

Can jQuery be used to change the functionality of a submit button, such as toggling between show, hide, and submit options?

I am having trouble toggling a button to either submit a form on click or reveal an input field, depending on whether the user clicks outside the input field to hide/collapse it. The issue arises when the user dismisses the input field and the submit butto ...

express-session fails to remove sessions from mongodb

account.js (node.js part) const express = require("express"); const router = express.Router(); router.post("/logout", (req, res) => { console.log("session: ", req.session); req.session.destroy(); console.log("session: ", req.session); res.send ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Guide to configuring Winston logging with Sequelize correctly

Currently, I am setting up winston with Sequelize and have the code snippet below: const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: path. ...

Steps to create a pop-up displaying a unique message ID retrieved from my database

My goal is to implement a pop-up message dialog on my website. When a user clicks on a reply icon, a pop-up message will appear with a textarea for the user to respond to a question they have been asked. The current issue is that clicking on the tag alway ...

Protractor encounters an "Error starting WebDriver session" message

After starting a server with webdriver-manager start, encountering an error when attempting to run protractor: Using the selenium server at http://127.0.0.1:4444/wd/hub [launcher] Running 1 instance of WebDriver ERROR - Unable to initiate a WebDriver sess ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Navigating through Laravel's API

My software is quite small and I utilize both laravel and vue.js. I am curious about the variance between routing via api.php and web.php within the routes folder. Could someone please enlighten me on the distinctions between these two scenarios? ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

What is the best way to create a Div element that functions as a button, becoming active when clicked while deactivating all other Div elements

function toggleButton1() { $("#button1").toggleClass("button-active button-inactive"); $("#button2").toggleClass("button-inactive button-active"); $("#button3").toggleClass("button-inactive button-active"); } function toggleButton2() { $("#butto ...

Is it possible to adjust the center of rotation in THREE.js TrackballControls so that it is not located at the center of the canvas

I'm currently using TrackballControls within THREE.js. The issue I am facing is that the center of rotation always remains in the center of the canvas. Is there a way to adjust this and move the center of rotation upwards? Here are my failed attempts: ...

javascript verify that the input is a valid JSON object

Seeking assistance with an if statement that checks for a json object: updateStudentData = function(addUpdateData) { var rowDataToSave; if(addUpdateData.data.row) { rowDataToSave = addUpdateData.data.row; } else { rowDataToSav ...

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

Utilizing cloud functions to distort an inappropriate image

I have a requirement to analyze any uploaded image for inappropriate content and blur it if necessary. The log this image is inappropriate indicates that the detection process is working correctly. However, I am not able to see any further logs which sugg ...

Obtaining the IP address of the client's request

In an effort to prevent others from wasting time in the future, I am sharing this post even though it's not really a question anymore. Objective: Obtain the client IP address and set specific values based on certain octets in the IP address. While w ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Sending data to the server using the $.post method with an

I am having some trouble creating a post using a customized model: public class CallbackPriorityItemModel { public int userID { get; set; } public int order { get; set; } public string name { get; set; } } Unfortunately, I can't seem to ...

The synchronization of sessions between Socket.IO and Express is proving to be a challenge as

I am currently facing an issue with connecting the sessions of my express API and socket.IO server. It appears that both are storing their sessions independently. The socket.IO server has the connections session, while the express server has the user qid s ...

When utilizing the map function with an array containing 168 objects in the state of a React application, a freeze of around 1

I encountered an issue when trying to update a property in a state array of objects after executing an axios.put request. Here is my code: States - useEffect //... const [volunteers, setVolunteers] = useState([]); //... useEffect(() => { async fu ...