我通過使用 Axios 并在陣列中回傳它來使用我的 API 中的資料。我可以使用簡單的 v-for 訪問 html 部分中的資料,但我也想訪問腳本部分中的資料,這可能嗎?我一直在嘗試參考它,但我找不到正確的使用方法。
我需要資料,因為我在視圖中實作了一個圖表,并且圖表的資料在腳本部分中定義。
我正在一個 .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: []
}},
技術堆疊:帶有 Axios 的 Vue 2.6、.NET 6 MVC
uj5u.com熱心網友回復:
如果我理解正確,如果你想要來自 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/[email protected]/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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/467512.html
標籤:javascript asp.net-mvc Vue.js 模型视图控制器 axios
上一篇:我正在使用html.beginform當我單擊一個按鈕時,我會轉到一個不同的操作,但我需要傳遞我在我的模型aspnetc#中的值
下一篇:視圖看不到/定義我的模型類