Programing

VueJS에서 Angular Service와 동등한 것은?

c10106 2022. 5. 18. 21:21
반응형

VueJS에서 Angular Service와 동등한 것은?

서버와 대화하고 데이터를 가져오는 모든 기능을 VueJS의 재사용 가능한 단일 파일에 넣고 싶다.

플러그인은 최선의 대안이 아닌 것 같다.템플릿에서 구성 요소를 줄임?

총 4가지 방법이 있다.

  • 상태 비저장 서비스: 그런 다음 혼합기를 사용하십시오.
  • 상태 저장 서비스: Vuex 사용
  • 서비스 내보내기 및 vue 코드에서 가져오기
  • 모든 javascript 글로벌 객체

api calls를 HTTP 클라이언트로 사용하고 있으며, api calls를 만들었다.gateways내 폴더src폴더와 나는 각 백엔드에 대한 파일을 넣어 다음과 같은 공리 인스턴스를 생성했다.

myApi.js

import axios from 'axios'
export default axios.create({
  baseURL: 'http://localhost:3000/api/v1',
  timeout: 5000,
  headers: {
    'X-Auth-Token': 'f2b6637ddf355a476918940289c0be016a4fe99e3b69c83d',
    'Content-Type': 'application/json'
  }
})

이제 구성 요소에서 다음과 같이 api에서 데이터를 가져오는 기능을 사용할 수 있다.

methods: {
 getProducts () {
     myApi.get('products?id=' + prodId).then(response =>  this.product = response.data)
  }
}

여러 구성 요소에서 이 방법을 다시 사용하려는 경우 vue.js 혼합물을 사용하십시오.

믹싱은 Vue 구성요소를 위해 재사용 가능한 기능을 배포하는 유연한 방법이다.혼합물 개체에는 모든 구성 요소 옵션이 포함될 수 있다.구성 요소가 혼합물을 사용할 때, 혼합물의 모든 옵션은 구성 요소 자체의 옵션으로 "혼합"된다.

그래서 믹싱에 메소드를 추가하면 모든 구성 요소에서 사용할 수 있고 믹싱이 혼합될 것이다.다음 예제를 참조하십시오.

// define a mixin object
var myMixin = {
  methods: {
     getProducts () {
         myApi.get('products?id=' + prodId).then(response =>  this.product = response.data)
      }
  }
}

// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
})

// alternate way to have a mixin while initialising
new Vue({
  mixins: [myMixin],
  created: function () {
    console.log('other code')
  }
})

나는 대부분 Vue Resource를 사용하고 있다.

1.I를 사용하여 API 끝점에 연결하는 새 파일을 생성함Vue.http.xxx자, 게시물을 출력하는 엔드포인트가 있다고 합시다.프로젝트에서 새 디렉터리 만들기, 나는 이 디렉터리를 부른다.services, 그런 다음 호출된 파일을 생성하십시오.PostsService.js- 내용은 다음과 같다.

import Vue from 'vue'

export default {
  get() {
    return Vue.http.get('/api/posts)
  }
}

그런 다음 이 서비스를 사용할 구성 요소로 가서 가져오십시오.

import PostsService from '../services/PostsService'

export default {
  data() {
   return {
     items: []
   }
  },
  created() {
   this.fetchPosts()
  },
  methods: {
   fetchPosts() {
    return PostsService.get()
      .then(response => {
        this.items = response.data
      })
   }
  }
}

이 방법에 대한 자세한 내용은 GitHub https://github.com/bedakb/vuewp/tree/master/public/app/themes/vuewp/app에서 내 리포(repo)를 확인하십시오.

앱 내 어디에서나 액세스할 수 있는 API 공급자를 만들 것을 제안한다.

단순하게 a 생성src/utils폴더와 그 안에는 파일이라는 것이 있다.api.js.

그 속에서 API를 개체나 ES6 정적 클래스로 통신하는 방법을 알고 있는 래퍼를 내보내십시오(클래스가 두렵지 않다면 후자의 모습과 작동 방식이 더 좋다).이 공급자는 당신이 좋아하는 모든 HTTP 요청 라이브러리를 사용할 수 있으며 당신은 나중에 코드베이스 전체를 검색하는 대신 하나의 파일(이 파일)을 변경하여 쉽게 바꿀 수 있다.다음은 공리 사용의 예로서, 다음 사이트에서 REST API를 사용할 수 있다고 가정해 보십시오.api.example.com/v1SSL 사용:

import axios from 'axios'

import { isProduction, env } from '@/utils/env'

const http = null // not possible to create a private property in JavaScript, so we move it outside of the class, so that it's only accessible within this module

class APIProvider {
  constructor ({ url }) {
    http = axios.create({
      baseURL: url,
       headers: { 'Content-Type': 'application/json' }
    })
  }

  login (token) {
    http.defaults.headers.common.Authorization = `Bearer ${token}`
  }

  logout () {
    http.defaults.headers.common.Authorization = ''
  }

  // REST Methods
  find ({ resource, query }) {
    return http.get(resource, {
      params: query
    })
  }

  get ({ resource, id, query }) {
    return http.get(`${resource}/${id}`, {
      params: query
    })
  }

  create ({ resource, data, query }) {
    return http.post(resource, data, {
      params: query
    })
  }

  update ({ resource, id, data, query }) {
    return http.patch(`${resource}/${id}`, data, {
      params: query
    })
  }

  destroy ({ resource, id }) {
    return http.delete(`${resource}/${id}`)
  }
}

export default new APIProvider({
  url: env('API_URL')  // We assume 'https://api.example.com/v1' is set as the env variable
})

그 다음, 당신 안에서.main.js파일 또는 Vue 앱을 부팅할 때 다음을 수행하십시오.

import api from '@/src/utils/api'

Vue.$api = api

Object.defineProperty(Vue.prototype, '$api', {
  get () {
    return api
  }
})

이제 Vue를 직접 가져오는 곳뿐만 아니라 Vue 앱의 어디에서나 액세스할 수 있다.

<template>
  <div class="my-component">My Component</div
</template>

<script>
export default {
  name: 'MyComponent',
  data () {
    return {
      data: []
    }
  },
  async created () {
    const response = await this.$api.find({ resource: 'tasks', query: { page: 2 } })

    this.data = response.data
  }
}
</script>

또는:

// actions.js from Vuex
import Vue from 'vue'

export async function fetchTasks ({ commit }) {
  const response = await Vue.$api.find({ resource: 'tasks', query: { page: 2 } })

  commit('SAVE_TASKS', response.data)

  return response
}

이게 도움이 되길 바래.

당신의 간단한 질문에 대한 답은 기능을 포함하고 있는 어떤 ES6 모듈(ANgular의 수업 방법과 동일)이 될 수 있으며, 그것을 ES6 수입과 수출을 이용하여 부품으로 직접 수입할 수 있다.구성요소에 주입될 수 있는 서비스는 없다.

당신은 당신의 모든 HTTP 서버 호출을 배치한 다음 그것들을 사용할 구성요소로 가져올 수 있는 당신만의 서비스를 만들 수 있다.

가장 좋은 방법은 복잡한 상태 관리 애플리케이션에 Vuex를 사용하는 것이다. Vuex에서는 항상 비동기적으로 실행된 다음 결과를 얻으면 돌연변이를 커밋하는 작업을 통해 모든 비동기 호출을 처리할 수 있기 때문이다.돌연변이는 국가와 직접 상호작용하며 불변한 방식(선호되는 방식)으로 업데이트한다.이것은 위엄 있는 접근이다.

다른 접근법도 있다.하지만 이것들은 내가 암호로 따르는 것들이야.

참조URL: https://stackoverflow.com/questions/41164672/whats-the-equivalent-of-angular-service-in-vuejs

반응형