【发布时间】:2017-08-22 12:16:47
【问题描述】:
基本上我想要一个全局的loadingbar 组件(包含在应用模板中)
这是我的loadingbar 组件
<template>
<div class="loadingbar" v-if="isLoading">
Loading ...
</div>
</template>
<script>
export default {
name: 'loadingbar',
props: ['isLoading'],
data () {
return {
}
}
}
</script>
<style scoped>
</style>
在main.js 中,我将此组件包含为
import LoadingBar from './components/LoadingBar.vue';
new Vue({
router,
data () {
return {
isLoading: true
};
},
methods: {
},
created: function () {
},
components: {
LoadingBar
},
template: `
<div id="app">
<LoadingBar :isLoading="isLoading"/>
<router-view></router-view>
</div>
`
}).$mount('#app');
我的目标是根据变量isLoading 的值显示加载组件。上面的代码工作正常。但我想使用来自其他组件的 set isLoading 变量(以便决定是否显示 loading 组件)。例如。在帖子组件
<template>
<div class="post container">
</div>
</template>
<script>
export default {
name: 'post',
data () {
return {
posts: []
}
},
methods: {
fetchPosts: function() {
// to show loading bar
this.isLoading = true;
this.$http.get(APIURL+'listpost')
.then(function(response) {
// to hide loading bar
this.isLoading = false;
console.log("content loaded");
});
}
},
created: function() {
this.fetchPosts();
}
}
</script>
<style scoped>
</style>
我们无法直接从main.js 访问isLoading,所以我决定使用Mixin,所以我将以下代码放入main.js
Vue.mixin({
data: function () {
return {
isLoading: false
};
}
});
然而,这允许我从任何其他组件访问isLoading,但我无法修改此变量。任何人都可以帮助我实现这一目标吗?
注意:我知道我可以通过在单个组件中包含
loadingbar来实现这一点(我试过了,它工作正常,但我不想这样做,因为每个组件都需要loadingbar所以我包括在主模板/组件中)
【问题讨论】:
标签: vuejs2 vue-component vue-router