在VueJS中的Http请求之后在运行时呈现组件



当应用程序启动时,我试图在Http请求后立即在VueJS中有条件地呈现组件。如果响应正常,我想呈现组件1,否则呈现组件2。我也想在点击上渲染组件

App.vue

<template>
<div id="app">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">

<div class="navbar-collapse" id="navbarsExample05">
<ul class="navbar-nav pl-md-5 ml-auto">
<li v-for="tab in tabs" v-bind:key="tab" v-bind:class="['nav-item nav-link', { active: currentTab === tab }]"
v-on:click="currentTab = tab">
{{ tab }}
</li>
</ul>

</div>
</nav>
<component v-bind:is="currentTabComponent" class="tab"></component>
</div>
</template>
<script>
import Comp1 from '../components/comp1'
import Comp2 from '../components/comp2'

export default {
name: 'App',
components: {
Comp1,
Comp2
},
data: function() {
return {
currentTab: 'Comp2',
tabs: ['Comp1', 'Comp2']
};
},
computed:{
currentTabComponent: function () {
function check(){
fetch('someHttpUrl')
.then(response => response.json())
.then(data => {
resolve('Comp1')
});
.catch(err => {
resolve('Comp2')
})
}
var result = check();
result.then(async function (data) {
return data
})
}
}
}
</script>

当我单击选项卡时,将加载右侧组件。但不是在应用程序启动时。是否有任何Vue方法来呈现异步组件?

不需要currentTabComponent计算方法。

您可以进行HTTP调用,并在调用完成后更新currentTab

类似这样的东西:

mounted() {
fetch('someHttpUrl')
.then(response => response.json())
.then(data => {
this.currentTab = 'Comp1'
});
.catch(err => {
this.currentTab = 'Comp2'
})
}

我还删除了名为check的方法,因为它看起来是多余的。

最新更新