Fetch method

Now, we are going to write the $fetch method. We will take most of the code we used in the created hook of the FAQ component:

  1. Implement the $fetch method using fetch:
      export async function $fetch (url) {
const response = await fetch(`${baseUrl}${url}`)
if (response.ok) {
const data = await response.json()
return data
} else {
const error = new Error('error')
throw error
}
}

We export it so we can use it in our plain JavaScript code too. The url parameter is now just the path of the query without the domain, which is now in our baseUrl variable--this allows us to change it easily without having to refactor each component. We also take care of the JSON parsing, since all the data from the server will be encoded in JSON.

  1. To make it available in all components, simply add it to the prototype of Vue (which is the constructor used to create components):
      export default {
install (Vue, options) {
// Plugin options
baseUrl = options.baseUrl

Vue.prototype.$fetch = $fetch
},
}
  1. Then, refactor the FAQ component to use our new special $fetch method in the created hook:
      this.loading = true
try {
this.questions = await this.$fetch('questions')
} catch (e) {
this.error = e
}
this.loading = false

Our code in the component is now shorter, easier to read, and more scalable since we can change the base URL easily.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.27.202