19.0 vue3 ref,reactive请求后的赋值问题以及解决方法
2023-09-11 14:22:28 时间
上一篇:
18.0 vue3 Vue Router的使用(1)_十一月的萧邦-CSDN博客
开发的过程中,我们一定会进行接口的对接,将响应的结果赋值给我们页面上需要展示或者操作的变量,在vue3中,我们可能会稍微的有点不适应,在赋值的过程中,使用了错误的做法,导致一直失败
错误示范:无论是使用ref声明的数组还是使用reactive声明的数组,此种写法都是错误的
<template>
<div>
list:{{ list }}
</div>
</template>
<script>
import {ref, reactive, toRefs} from "vue";
export default {
name: "Test",
setup() {
let list = ref([])
getList()
async function getList() {
list = await httpGetList()
}
//
// let list = reactive([])
// getList()
//
// async function getList() {
// list = await httpGetList()
// }
function httpGetList() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([1, 2, 3, 4, 5])
}, 500)
})
}
return {
list
}
}
}
</script>
正确写法:
方法1
let list1 = ref([])
getList1()
async function getList1() {
list1.value = await httpGetList()
}
方法2
let list2 = reactive([])
getList2()
async function getList2() {
let resp = await httpGetList()
list2.push(...resp)
}
方法3
let data = reactive({
list3: []
})
getList3()
async function getList3() {
data.list3 = await httpGetList()
}
个人比较推荐 方法3或者方法1,优先使用方法3 ,对于对象也是一样的操作哦!
完整代码
<template>
<div>
list:{{ list }}
</div>
<div>
list1:{{ list1 }}
</div>
<div>
list2:{{ list2 }}
</div>
<div>
list3:{{ list3 }}
</div>
</template>
<script>
import {ref, reactive, toRefs} from "vue";
export default {
name: "Test",
setup() {
// let list = ref([])
// getList()
//
// async function getList() {
// list = await httpGetList()
// }
//
let list = reactive([])
getList()
async function getList() {
list = await httpGetList()
}
let list1 = ref([])
getList1()
async function getList1() {
list1.value = await httpGetList()
}
let list2 = reactive([])
getList2()
async function getList2() {
let resp = await httpGetList()
list2.push(...resp)
}
///
let data = reactive({
list3: []
})
getList3()
async function getList3() {
data.list3 = await httpGetList()
}
function httpGetList() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([1, 2, 3, 4, 5])
}, 500)
})
}
return {
list,
list1,
list2,
...toRefs(data)
}
}
}
</script>
<style scoped>
</style>
下一篇:
相关文章
- Vue3 getters打印结果是Proxy对象,怎么获取其中的值?
- 你真的会用Vue3的setup函数?
- Vue2.7正式发布!代号为:Naruto(火影忍者),原生支持 Composition API +终于可以在Vue2项目中使用Vue3的新特性了,真香~
- 初始化创建安装 vue3工程项目的3种方法!超详细
- vue3 - 引入自定义插件的组件的具体写法
- vue3 - 在单独的项目制作自定义组件插件,支持vite【前提不要使用webpack专属语法】,并引入插件 -心得
- vue3 - .eslintignore 配置忽略指定文件或者文件夹的eslint检查报错
- vue3 - .eslintrc.js配置,包括开启debugger 等能力
- vue3 - import js文件eslint报错-解决
- vue3 watch 监听 flush post 作用?
- vue3+ts创建二维数组响应式变量及赋值
- Vue3学习笔记(二)——组合式API(Composition API)
- 从0搭建Vue3组件库(一): 开篇
- Vue3 + Ts 封装axios
- vue2和vue3有哪些区别和不同1
- vue3快速入门-Teleport传送(瞬移组件)
- Vue2和Vue3的区别和变化
- Vue3 reactive / customRef 快速理解掌握
- Vue3使用IP地址访问(解决 ERR_CONNECTION_REFUSED)