在设置选项内更新 axios 响应回调中的反应数据 - Vue 3
Update a reactive data in axios response callback inside setup option - Vue 3
我正在组件的 Setup 方法中进行 Axios 调用。然后我想设置一个名为 books 的变量。在 vue 2 中,我会在创建的挂钩中进行调用,然后使用 this
来设置变量。在 vue 3 中,setup 方法中没有可用的 this
那么如何在 axios 调用之外访问数据?我想获取一组书籍,然后将其设置为 books 变量。这将如何完成,在 Vue 3 中是否有更好的方法来做到这一点?我的设置方法如下:
setup() {
let books = reactive<Array<Book>>([])
HTTP.get('/books')
.then(response => {
//Normally here I would do this.books
books = response.data
})
.catch(function (error) {
console.log(error);
})
return { books }
}
根据 composition api docs :
reactive
Takes an object and returns a reactive proxy of the original ...
...
ref
Takes an inner value and returns a reactive and mutable ref object. The ref object has a single property .value that points to the inner value ...
所以 reactive
函数应该有一个内部 属性 :
setup() {
let state = reactive<Array<Book>>({books:[]})
HTTP.get('/books')
.then(response => {
state.books = response.data
})
.catch(function (error) {
console.log(error);
})
return { books:toRef(state,'books') }
}
或使用 ref
setup() {
let books = ref<Array<Book>>([])
HTTP.get('/books')
.then(response => {
books.value = response.data
})
.catch(function (error) {
console.log(error);
})
return { books }
}
我正在组件的 Setup 方法中进行 Axios 调用。然后我想设置一个名为 books 的变量。在 vue 2 中,我会在创建的挂钩中进行调用,然后使用 this
来设置变量。在 vue 3 中,setup 方法中没有可用的 this
那么如何在 axios 调用之外访问数据?我想获取一组书籍,然后将其设置为 books 变量。这将如何完成,在 Vue 3 中是否有更好的方法来做到这一点?我的设置方法如下:
setup() {
let books = reactive<Array<Book>>([])
HTTP.get('/books')
.then(response => {
//Normally here I would do this.books
books = response.data
})
.catch(function (error) {
console.log(error);
})
return { books }
}
根据 composition api docs :
reactive
Takes an object and returns a reactive proxy of the original ...
...
ref
Takes an inner value and returns a reactive and mutable ref object. The ref object has a single property .value that points to the inner value ...
所以 reactive
函数应该有一个内部 属性 :
setup() {
let state = reactive<Array<Book>>({books:[]})
HTTP.get('/books')
.then(response => {
state.books = response.data
})
.catch(function (error) {
console.log(error);
})
return { books:toRef(state,'books') }
}
或使用 ref
setup() {
let books = ref<Array<Book>>([])
HTTP.get('/books')
.then(response => {
books.value = response.data
})
.catch(function (error) {
console.log(error);
})
return { books }
}