简体   繁体   中英

Vuejs: Use stored data withing nuxt pages

I'm using Nuxt as my front server and in pages folder there's an index page which I want to use vue-material autocomplete package in it. For that purpose, I have a plugin that imports my package as following:

import Vue from 'vue'
Vue.config.productionTip = false

import VueMaterial from 'vue-material'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default.css'

Vue.use(VueMaterial)

Then in my page I have the following script which get the data from back and fetches it into the store's state:

export default {
  async fetch (context) {
    let { data } = await context.$axios.get('http://127.0.0.1:8000/')
    context.store.commit('my_data', data)
  },

Now below this I have to use something like this which is suggested by vue-material doc :

 data: () => this.$store.dispatch('my-data'), <- Doesn't work
  methods: {
    getMyData (searchTerm) {
      this.mydata = new Promise(resolve => {
        window.setTimeout(() => {
          if (!searchTerm) {
            resolve(this.my_data)
          } else {
            const term = searchTerm.toLowerCase()

            resolve(this.my_data.filter(({ name }) => name.toLowerCase().includes(term)))
          }
        }, 500)
      })
    }
  }

As you can see I want to load the the date that is previously saved in store. And none of the commands like this.$store.dispatch works. It always raise this error tat this is not defined.

I'm not sure if what I'm trying to do is the best way for this problem whatsoever but the point is that when I use a custom dictionary instead of data the autocomplete works fine.

You can use asyncData to load the data from the store ( https://nuxtjs.org/guide/async-data )

async asyncData(context) { 
  let result = await context.store.dispatch('my-data')
  return {
    data: result
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM