Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

动态传值给require加载vue组件?

Vue.component(name, function (resolve) {
require([path], resolve)
})

name path都是传入的值 然后动态注册模块
但require是被强制静态化的导致path传了无效

问高人说用异步组件,去加载。
无奈技术有限 无入手方向或头绪
请给位指点 一二 或是贴码 更好
多谢各位


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

首先列出参考:

  1. Vue异步组件

  2. Webpack Dynamic Require

  3. Webpack Code Spliting

然后用vue-cli的webpack-simple template写了个简单的demo:
仅仅是将App.vue丢到了src/component下面(目的是为了体现webpack的context解析),然后修改import的方式为dynamic require。
其实要动态require大概的意思就是要告诉webpack上下文,不然webpack在编译时并不知道这个module是什么(因为是个变量)。

main.js

import Vue from 'vue'
// import App from './App.vue'

const name = 'App.vue'

const App = (resolve) => {
    require.ensure([], (require) => {
        resolve(require.context('./component', false, /.vue$/)(`./${name}`));
    }, 'app');
};

new Vue({
  el: '#app',
  render: h => h(App)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...