vue学习时遇到的问题(一)

1.vue的异步组件,require()方法
作用是:在需要使用的时候,从 根目录/components/HelloWorld.vue 加载组件
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: resolve => require(['@/components/HelloWorld'], resolve),
    }
  ]
})
如果不用懒加载代码应该是这样:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})
 
2.关于export default 和 export
一、export和export default
export和export default都用于导出常量、函数、文件、模块等,区别是:
    1、在一个JS文件中,export可以有多个;export default只能有一个;
    2、它们的引用方式不同;
 
二、import用于引入一个JS文件:
    1、如import引入的是依赖包,则不需要相对路径;
    2、如import引入的是自定义的JS文件,则需要相对路径;
    3、import使用export导出的需要用{},使用export default导出的不需要{};
 
例如:export导出的引用
//d1.js
//d1.js是用export导出的
export const str = 'hello world'
export function f0(a){
    return a+1
}
export const f1 = (a,b) => {
    return a+b
}
export const f2 = (function () {
    return 'hello'
})()
引用方式:
//d2.js
//在d2.js中引用d1.js,d1.js是使用export导出的变量和函数,引用时要使用{};
import { str,f0,f1,f2 } from 'd1' //名字要和export相同,d2.js和d1.js在同目录,如不同目录则 from '../../d1.js',扩展名可以不写
const a = f1(1,2)
//也可以写成:
import {str} from 'd1'
import {f1} from 'd1'
 
用export default导出:
//d3.js 
//用export default导出,JS文件中只能有一个 
export default const str = 'hello world'
引用:
//d4.js 
//引用d3.js,使用export default导出的,引用时不要{} 
import str from 'd3' //名字可以任意
 
export default 批量导出:
//修改后的d3.js
export const str = 'hello world'
export function f0(a){
    return a+1
}
export const f1 = (a,b) => {
    return a+b
}
export default {
   str,
   f0,
   f1
}
引用:
//修改d4.js 
import d from 'd3' const a = d.f0(45)
 
3.对vue项目的大体理解

猜你喜欢

转载自www.cnblogs.com/ShiningArmor/p/10862927.html
今日推荐