
最后,让我们来测试一下吧。测试代码如下,用setTimeout来模拟异步请求。
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg: ''
}
},
mounted() {
this.$loading.show()
setTimeout(()=>{
this.$loading.close()
this.msg = '加载完辽!'
},3000)
}
}
</script>
奶思!测试成功!
React部分
在此之前,我先介绍一下react中的高阶组件(HOC)
高阶组件
在React中,多个不同的组件中如果需要用到相同的功能,这个解决方法,通常有Mixin和高阶组件。但是由于Mixin过多会使使得组件难以维护,在React ES6中Mixin不再被支持。高阶组件是一个接替Mixin实现抽象组件公共功能的好方法。高阶组件其实是一个函数,接收一个组件作为参数,返回一个包装组件作为返回值,类似于高阶函数。
具体实现
先用create-react-app 生成一个测试脚手架,高阶组件目录如下图所示

index.css主要是loading的样式,index.js的代码如下
import React from 'react';
import './index.css'function hoc(ComponentClass) {
return class HOC extends ComponentClass {
render() {
if (!this.state.loading) {
console.log(this.state.loading)
return super.render()
}
else {
return (<div>
<div className="container">
<div className="loading"></div>
</div>
</div>)
}
}
}
}
export default hoc
我们定义了一个hoc函数,接受一个组件作为参数。通过this.state来操作组件的state属性,通过super.render()来渲染组件。最后导出hoc函数。然后在组件中引入,如下
import hoc from '../hoc/loading/index'class Home extends Component {
constructor(props) {
super(props)
this.state = {
msg: '还没加载好',
loading: true
}
}
render() {
return (
<div>
{this.state.msg}
</div>
);
}
componentDidMount() {
let loading = this.state.loading
setTimeout(() => {
this.setState({
loading: !loading,
msg: '加载完辽!'










