API
लिखने के तरीके सीधे घटकों में कोड लाइनों को बढ़ाते हैं और पढ़ने में मुश्किल बनाते हैं। जहां तक मेरा मानना है कि author
विधियों को Service
में अलग करने का सुझाव दे रहा है।
चलो एक ऐसा मामला लें जहां आपको top posts
लाने और डेटा पर काम करना है। यदि आप घटक में ऐसा करते हैं तो यह पुनः उपयोग करने योग्य नहीं है, आपको इसे अन्य घटकों में डुप्लिकेट करना होगा जहां कभी भी आप इसका उपयोग करना चाहते हैं।
export default {
data:() => ({
top: [],
errors: []
}),
// Fetches posts when the component is created.
created() {
axios.get(`http://jsonplaceholder.typicode.com/posts/top`)
.then(response => {
// flattening the response
this.top = response.data.map(item => {
title: item.title,
timestamp: item.timestamp,
author: item.author
})
})
.catch(e => {
this.errors.push(e)
})
}
}
तो जब आप एक और घटक में top post
लाने की जरूरत है आप कोड की नकल करने की है।
अब में API methods
डालें।
api.js file
const fetchTopPosts = function() {
return axios.get(`http://jsonplaceholder.typicode.com/posts/top`)
.then(response => {
// flattening the response
this.top = response.data.map(item => {
title: item.title,
timestamp: item.timestamp,
author: item.author
})
}) // you can also make a chain.
}
export default {
fetchTopPosts: fetchTopPosts
}
तो तुम ऊपर API methods
किसी भी घटक तुम चाहो में इस्तेमाल करते हैं।
इस के बाद:
import API from 'path_to_api.js_file'
export default {
data:() => ({
top: [],
errors: []
}),
// Fetches posts when the component is created.
created() {
API.fetchTopPosts().then(top => {
this.top = top
})
.catch(e => {
this.errors.push(e)
})
}
}
स्रोत
2017-08-23 14:01:21
धन्यवाद एक बहुत!मैं अब समझता हूँ। –
किसी ने भी इसके बारे में एक दिलचस्प लेख लिखा: https://vuejsdevelopers.com/2017/08/28/vue-js-ajax-recipes/ –