【发布时间】:2022-01-19 07:05:18
【问题描述】:
我的名字是 DP,我有 2 年的 Vue2 经验,但我是 Vue3 的新手。我最近正在学习 Vue3,因为我发现“设置(组合 API)”就像我用其他语言做的“控制器(在 MVC 中)”一样,所以我试图以 MVC 方式构建我的测试 Vue3 项目,但我解决一些问题有人可以帮忙吗?谢谢!
MVC 计划
M - use class
V - use <template> ... </template>
C - use setup
我的问题
工作:在 setup() 中使用 loadTopic_inSetup().then() 是有效的,因为 topicList_inSetup 也在 setup() 中定义。
不起作用:在设置中使用 loadTopic_inModel() 不起作用,我猜是某种数据保留问题,因为在控制台中我可以看到已经从 API 获得的数据
如您所见,我不是 js/ts 专家,我是后端开发人员,所以如果您知道如何做,请多多帮助。
顺便说一句,VUE 很受欢迎,我喜欢它。
我的代码
//APIBased.ts
import { ajax } from "@/lib/eeAxios"
export class APIBased {
//load data with given url and params
loadData(apiPath: string, params?: object): Promise<any> {
apiPath = '/v1/'+apiPath
return ajax.get(apiPath, params)
}
}
//主题.ts 从“./APIBased”导入 { APIBased }; 从 'vue' 导入 { ref }
export class Topic extends APIBased {
//try keep data in model
topicList: any = ref([]);
constructor() {
super()
}
//direct return ajax.get, let setup do the then+catch
loadTopic_inSetup() {
return super.loadData('topics', { t_type_id: 1 })
}
//run ajax get set return data to this.topicList, keep data in model
loadTopic_inModel() {
super.loadData('topics', { t_type_id: 1 }).then((re) => {
console.log(re.data)
this.topicList = re.data
})
}
}
//EETest.vue
<template>
<EELayoutMainLayout>
<template v-slot:mainContent>
<h1>{{ "Hello Vue3 !!" }}</h1>
<hr/>
{{to.topicList}} //not working... just empty array
<hr/>
{{topicList_inSetup}} //working... topic list return from API show here.
</template>
</EELayoutMainLayout>
</template>
<script lang="ts">
import { defineComponent, getCurrentInstance, ref } from 'vue'
import EELayoutMainLayout from '@/components/eeLayout/EELayoutMainLayout.vue'
import { Topic } from "@/models/Topic";
export default defineComponent({
name: 'EETest',
props: {
},
setup() {
let topicList_inSetup = ref([])
const to = new Topic()
//try keep data in setup, it's working
to.loadTopic_inSetup().then((re) => {
topicList_inSetup.value = re.data
console.log(re.data)
})
//try keep data in model, the function is run, api return get, but data not show, even add ref in model
to.loadTopic_inModel()
return {
topicList,
to,
}
},
components: {
EELayoutMainLayout,
},
})
</script>
【问题讨论】:
-
我在
Topic类中看到的一件事,topicList是一个引用,因此您需要将响应数据分配给它的值。
标签: model-view-controller axios vuejs3 vue-composition-api