1. 第一例
- const Home = resolve => {import("@/components/home/home.vue").then( module => {
- resolve(module)
- }
- }
注:(上面 import 的时候可以不写后缀)
- export default [{
- path: '/home',
- name:'home',
- component: Home,
- meta: {
- requireAuth: true, // 添加该属性可以判断出该页面是否需要登录显示
- },
- }]
2. 第二例
- const router = new Router({
- routes: [
- {
- path: '/home',
- component: (resolve)=> {
- require(['../components/home/home'], resolve) // 省去了在上面去 import 引入
- }
- }
- ]
- })
3. 第三例, 这也是推荐的一种
- // r 就是 resolve// 路由也是正常的写法 这种是官方推荐的写的 按模块划分懒加载
- const Home = r => require.ensure([], () => r(require('../components/home/home')), 'home');
- const router = new Router({
- routes: [
- {
- path: '/home/home',
- component: Home,
- name: 'home' ,
- }
- ]
- })
下面给大家介绍下 vue+webpack 实现异步组件加载的代码, 具体代码如下所示:
- <input type="button" @click="showchild" value="show"> // 点击按钮后, show 为真, 先获取 child 组件, 再渲染 div 内容
- <div id="contain" v-if="show">
- <child></child>
- </div>
JS
- data () {
- return {
- msg: 'Welcome to Your vue.js App',
- show:false
- }
- },
- methods: {
- showchild:function(){
- this.show=true;
- }
- },
- components: {
- 'child': function(resolve) {
- require(['./components/child.vue'], resolve);
- }
- }
注意: 加载异步组件的时候, 组件名后边的. vue 不要忽略. 这个例子应该比较直观了. 点击按钮之后改变了变量 show 的布尔值为真, 由于 child.vue 是异步组件, 所以会先 ajax 获取组件然后渲染.
总结
以上所述是小编给大家介绍的 vue+webpack 实现异步加载三种用法, 希望对大家有所帮助, 如果大家有任何疑问请给我留言, 小编会及时回复大家的. 在此也非常感谢大家对脚本之家网站的支持!
来源: http://www.jb51.net/article/138834.htm