Axios에서 VUE JS 데이터 액세스
vue JS(Vuetify) 앱에서 div의 콘텐츠를 응답으로 채우고 싶다는 Ajax 요청을 하는데 인스턴스의 데이터에 액세스하는 데 어려움이 있습니다.지금까지 본 예에서는 모두 데이터 개체를 가리키는데 이 오류가 발생합니다.
Unable to set property 'message' of undefined or null reference
앱은 매우 간단합니다.
main.filename:
import Vue from 'vue'
import App from './App.vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)
new Vue({
el: '#app',
render: h => h(App)
})
App.vue
export default {
data () {
return {
....
message: '',
order: {},
...
},
methods: {
send: function() {
axios.post(this.api+"orders",this.order).then(function(response) {
this.message = "Your payment was successful";
...
}
}
}
이.order는 Axios의 post method로 문제없이 접근할 수 있지만, 반환된 약속을 처리하는 익명 함수는 제가 본 예와 달리 이.message에 접속하는 데 문제가 있는 것 같습니다.
내가 여기서 다르게 하고 있는 건 뭐지?
저는 당신의 문제에 대한 해결책을 생각해 낼 수 있습니다.
1) 다음에 대한 참조를 작성할 수 있습니다.this
사용하세요.
send: function() {
let self = this
axios.post(this.api + "orders", this.order).then(function(response) {
self.message = "Your payment was successful"
}
}
2) ANarrow function
를 사용할 수 있습니다.this
Vue 인스턴스를 가리킵니다.
send: function() {
axios.post(this.api + "orders", this.order).then(response => {
this.message = "Your payment was successful"
}
}
3) 사용bind
(물건을) 할당하다this
현재 Vue 인스턴스가 됩니다.
send: function() {
axios.post(this.api + "orders", this.order).then(function(response) {
this.message = "Your payment was successful"
}.bind(this))
}
문제는 이 라인입니다.
axios.post(this.api+"orders",this.order).then(function(response) {
예를 들어,this
그러나 두 번째 수준의 중첩된 함수식을 사용함으로써 다른 다이내믹에 액세스하게 됩니다.this
당신이 생각하는 것보다 더요.
기본적으로는send
Vue 객체의 메서드입니다만,this
내부에서는 사전 스코프가 적용되지 않습니다.function
표현, 내부만=>
함수는 잘못 알고 있습니다.this
전달처의 콜백 참조Promise.prototype.then
.
자세한 내용은 다음과 같습니다.
methods: {
send: function() {
// here: `this` technically refers to the `methods` object
// but Vue lifts it to the entire view object at runtime
axios.post(this.api + "orders", this.order)
.then(function(response) {
// here: `this` refers to the whatever object `the function is called on
// if it is called as a method or bound explicitly using Function.prototype.bind
// the Promise instance will not call it on anything
// nor bind it to anything so `this` will be undefined
// since you are in a module and modules are implicitly strict mode code.
this.message = "Your payment was successful";
});
}
}
대신 이것을 사용해 보세요.
export default {
data() {
return {
message: "",
order: {},
},
methods: {
send: function() {
// here: `this` technically refers to the `methods` object
// but Vue lifts it to the entire view object at runtime
axios.post(this.api + "orders", this.order).then(response => {
// here: this refers to the same object as it does in `send` because
// `=>` functions capture their outer `this` reference statically.
this.message = "Your payment was successful";
});
}
}
}
더 좋은 것은
export default {
data() {
return {
message: "",
order: {},
},
methods: {
async send() {
const response = await axios.post(`${this.api}orders`, this.order);
this.message = "Your payment was successful";
}
}
}
두 번째 예에서는 최근에 표준화된 JavaScript를 사용합니다.async/await
콜백의 필요성을 완전히 추상화했기 때문에 포인트는 흐지부지됩니다.
여기서 제안하는 것은 질문과 관련된 것이 아니라 Promise 기반 코드를 작성할 때 선호되는 방법이어야 하기 때문입니다.다른 언어 기능을 사용하여 코드를 작성할 수 있는 경우입니다.Promise를 사용하면 코드가 명확해집니다.
단, 이 답변의 요점은 이 답변의 범위입니다.this
언급.
언급URL : https://stackoverflow.com/questions/45216998/accessing-vue-jss-data-from-axios
'programing' 카테고리의 다른 글
JUnit 어설션에서의 어레이 비교, 간결한 임베디드 방식 (0) | 2022.08.13 |
---|---|
Vuex에서 재사용 가능한 작업 가져오기 (0) | 2022.08.13 |
@keyup 이벤트에 의해 이 메서드가 트리거되지 않는 이유는 무엇입니까? (0) | 2022.08.13 |
버튼을 Vue.js로 전환하려면 어떻게 해야 합니까? (0) | 2022.08.13 |
모든 어레이 요소를 0으로 초기화할 수 있는 숏컷이 있습니까? (0) | 2022.08.13 |