A
A
alestro2022-03-04 21:49:30
Vue.js
alestro, 2022-03-04 21:49:30

Why is state reset when switching components in vue3?

On the component page, projects are pulled from the api server, but when you return to the component page after switching to another route, the collection with projects is reset and loaded again. How to fix it?
script section:

export default {
  name: "Projects",
  components: {SearchBar, AddProjectModal, ProjectCard, PageWrapper, Header, Sidebar},
  data() {
    return {
      searchResults: ref([]),
      hideCloseBtn: true,
    }
  },
  setup() {
    return {
      projects: ref(findProjects({load: 'photos'}))
    }
  },
  methods: {
    async load() {
      await this.projects.load()
    }
  }
}

class ProjectCollection {
    *[Symbol.iterator]() {
        for (let element of this._elements) {
            yield element
        }
    }
    constructor(url) {
        this._elements = []
        this._nextUrl = url
        this._count = 0
    }

    add(element) {
        this._elements.push(element)
    }

    addMany(elements) {
        this._elements.push(...elements)
    }

    _map(data){
        if (data !== []) {
            this._nextUrl = data.next
            this._totalResults = data.count
            this.addMany(data.results)
        }
    }

    get length() {
        return this._elements.length
    }

    isEmpty() {
        return this._elements.length === 0
    }

    get count() {
        return this._count
    }

    hasMore() {
        return this._nextUrl !== null
    }

    async load() {
        if (this.hasMore()) {
            this._map((await axios.get(this._nextUrl)).data)
        }
    }
}
function findProjects(query = {}) {
    return new ProjectCollection(_url('project', query).toString())
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2022-03-04
@Fragster

Learn this: https://v3.ru.vuejs.org/ru/api/built-in-components...
https://router.vuejs.org/guide/migration/#router-v
... better push data from api to vuex store https://vuex.vuejs.org/en/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question