结论
require(['../ccc.js'],function(){})是异步加载
require('../ccc.js') 同步加载
require参数只是一个路径时,是同步,参数是一个数组时就是异步加载
今天遇到一个问题,点一个按钮,根据传递的参数展示不同组件,同一个按钮点击第一次,组件总是获取不到,报错说这个组件不存在,里面的方法自然也是不能调用了,但是老版本的代码不会出现这个问题,后经排查是这个require函数调用方法不同,导致有的版本代码可以正常执行,有的版本第一次加载会报错,如下
<component
:is="myComponent"
ref="currentComponent"
/>
export default {
data(){
return{
myComponent:'AsyncCom',
}
},
props:{
cnpPath:{
type:String,
default:''
}
},
watch: {
cnpPath(newval) {
//1.require('***') 同步加载 可以正常获取到组件
Vue.component('AsyncCom', require('/src/views' + newval).default)
this.$nextTick(()=>{
console.log(this.$refs.currentComponent)//查看打印结果是当前的组件
})
//2. require(['../ccc.js'],function(){})是异步加载
Vue.component('AsyncCom', (resolve)=>require(['/src/views'+ newval],resolve ))
this.$nextTick(()=>{
console.log(this.$refs.currentComponent)//打印结果undefined
})
},
methods:{
}
}