반응형
vue의 콜백에서 로컬 컴포넌트 변수에 액세스하는 방법
api rest 명령을 사용하여 컴포넌트 변수를 설정하려고 합니다.아래의 handleResponse()라는 자체 파일에 있는 함수를 통해 모든 응답을 처리하고 싶었습니다.
// api/tools/index.js
function handleResponse (promise, cb, cbError) {
var cbErrorRun = (cbError && typeof cb === "function")
promise.then(function (response) {
if (!response.error) {
cb(response)
}
else if (cbErrorRun) {
cbError(response)
}
}).catch(function (error) {
console.log(error)
if (cbErrorRun) {
var responseError = {
"status": 404,
"error": true,
"message": error.toString()
}
cbError(responseError)
}
})
}
export {handleResponse}
내 컴포넌트 파일에 이 파일이 있습니다.
.... More above....
<script>
import { fetchStock } from '@/api/stock'
export default {
data () {
return {
stock: {},
tabs: [
{
title: 'Info',
id: 'info'
},
{
title: 'Listings',
id: 'listings'
},
{
title: 'Company',
id: 'company'
}
],
}
},
validate ({params}) {
return /^\d+$/.test(params.id)
},
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
function(response) { //on successful data retrieval
this.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
}
</script>
현재 코드는 다음과 같은 오류를 표시합니다. "Uncatched (in promise)"TypeError: undefinedAc의 속성 'stock'을 설정할 수 없습니다.fetchStock 함수로 전달한 콜백 내에서 더 이상 'this'에 액세스할 수 없기 때문에 발생하는 현상이라고 생각합니다.현재 handleResponse 레이아웃을 변경하지 않고 이 문제를 해결하려면 어떻게 해야 합니까?
이 방법을 시도해 보세요.
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
var self = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
화살표 함수는 다음을 유지 및 사용하기 때문에 화살표 함수를 콜백에 사용할 수 있습니다.this
포함 범위:
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
(response) => { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
(responseError) => { //on error
console.log(responseError)
}
)
}
또는 할당할 수 있습니다.const vm = this
n 이와 같은 콜백 전에 메서드를 시작합니다.
vm은 "View Model"을 나타냅니다.
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
const vm = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
를 사용하는 것을 권장합니다.
const
와는 반대로var
에서vm
가치를 분명히 하기 위한 선언vm
상수입니다.
언급URL : https://stackoverflow.com/questions/50313922/how-to-access-local-component-variable-from-a-callback-in-vue
반응형
'sourcecode' 카테고리의 다른 글
어레이 응답을 vue.js 및 larabel로 표시하는 방법 (0) | 2022.08.13 |
---|---|
VueJ: 트리거 시 커스텀 Socket.io에서 내보내는 기능이 처리되지 않음 (0) | 2022.08.13 |
b-table 구성 요소의 모든 열에 대해 정렬을 활성화할 수 있습니까? (0) | 2022.08.13 |
vue.js 2의 입력 유형 텍스트에 연산자 3진수를 추가하려면 어떻게 해야 합니까? (0) | 2022.08.13 |
Vue 인라인 템플릿이 메서드 또는 데이터를 찾을 수 없음 (0) | 2022.08.13 |