效果:
父元件程式碼
<template> <el-container v-loading="loading" class="container" element-loading-background="rgba(1,35,54, 0.8)"> <h1>這是父元件</h1> <HelloWorld msg="Welcome to Your Vue.js App" @loadTrue="loadTrue" @loadFalse="loadFalse"/> </el-container> </template> <script> import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'HomeView', components: { HelloWorld }, data() { return { loading: false, } }, methods:{ loadTrue(){ this.loading = true; }, loadFalse(){ this.loading = false; }, } } </script> <style scoped> .container{ width: 100%; height: 800px; position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: #CAE1FF; } </style>
子元件程式碼
<template> <div class="hello"> <h1>{{ msg }}</h1> 這是子元件 <div style="margin-top: 20px;"> <button @click="getList">模擬從後臺獲取資料</button> </div> </div> </template> <script> let that export default { name: 'HelloWorld', props: { msg: String }, created(){ that = this }, methods:{ getList(){ this.$emit('loadTrue'); setTimeout(function(){ that.$emit('loadFalse'); },1000) } } } </script> <style scoped> .hello{ width: 50%; height: 400px; background-color: #FFF0F5; } </style>