Can you change state in VueJS more slowly?

Viewed 50

I have written a program that takes a grid and using recursive backtracking to generate a maze. The thing is, I want to be able to visualize the maze generation as it is happening. Right now, Vue waits until the generation is completed to update the UI and display the final result. Is there a way to change when Vue updates the UI?

2 Answers

Make a method that generates only one section of the maze and then calls a method to generate the next section in a setTimeout. That way Vue will render one section at a time, and you can control how quickly the maze is visually constructed.

Yes, this can be achieved, Vue offers reactive system, i.e. when you update some portion of your data model then the view layer (HTML elements) update too. Let's say your maze's data structure is an array of objects and the visual representation of this data consists of template with v-for. Example:

<template>
 <div v-for="(item, index) in getMazeData" :key="index">{{ item.name }}</div>
</template>

So in order to show the progress of your data generation you should mutate the data array when some portion of the data for the whole thing is ready. If you start with an empty array, you can simply push new elements to it and the reactivity system will update the DOM itself. Example:

<script>
export default {
  methods: {
    generateMaze() {
        // ... some data generation happens here and then add new element to data store
        this.maze.push({... some fresh data})
    }
  },
  computed: {
    getMazeData() {
     return this.mazeData
    }
  },
  mounted() {
    this.generateMaze()
  },
  data() {
    return {
      mazeData: []
    };
  },
};
</script>

If you wish you can also apply some delay before pushing new elements to the array. Example:


methods: {
    generateMaze() {
        // ... some data generation happens here and then add new element to data store
        setTimout(()=> {
            this.maze.push({... some fresh data})
        },100)
    }
  },

And finally this can be achieved with Vuex store too, where you commit mutation when some data is ready.

Related