在脚本标签内使用Axios返回对象



我通过使用Axios并在数组中返回它来使用来自API的数据。我可以访问数据在html部分与一个简单的v-for,但我也想访问数据内的脚本部分,这是可能的吗?我一直试图引用它,但我找不到正确的方法来使用它。

我需要这些数据,因为我在视图中实现了一个图形,并且该图形的数据在脚本部分中定义。

我在一个。cshtml文件中的MVC 6项目工作。我已经有了可以从API访问数据的控制器函数,并且可以通过引用模型进行访问,但是因为每个控制器方法只能访问一个API端点,所以我想实现Axios。

我用过的代码:

created() {
axios.get('https://localhost:44332/api/clients')
.then(response => { this.clients = response.data})
.catch(error => {console.log(error)})}

Vue设置:

let app = new Vue({
el: '#app',data() {
return {
clients: []
}},

技术栈:Vue 2.6 with Axios, .NET 6 MVC

如果我理解正确的话,如果你想要vue的数据,你可以使用$data:

let app = new Vue({
el: '#app',
data() {
return {
clients: [],
}
},
async created() {
await axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => { this.clients = response.data})
.catch(error => {console.log(error)})
},
})
function getData() {
setTimeout(() => console.log('outside of vue ', app.$data.clients), 500)
}
getData()
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id='app'>
<div v-for="(client, i) in clients" :key="i">
{{ client }}
</div>
</div>

最新更新