目录
[ES6 模块化导出导入](#ES6 模块化导出导入)
[export default](#export default)
前言
前面学习了js,引入方式使用的是<script s"XXX.js">,今天来学习引入文件的其他方式,使用ES6 模块化编程,学习组件化编程中的全局注册和局部注册的方法。
复习
回顾前面学习内容,用<script s"XXX.js">引入js文件
在html文件中引入js文件
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="learn.js">
</script>
<script>
console.log(this.content)
learn()
</script>
</body>
js文件
javascript
const content = "模块化";
const learner = "MRJJ_9";
function learn()
{
console.log(`${learner}在学习${content}`);
}
ES6 模块化导出导入
先导出js文件
javascript
export const content = "模块化";
export const learner = "MRJJ_9";
export function learn()
{
console.log(`${learner}在学习${content}`);
}
简单写法,也可以写成下面这样的
解构赋值
import * as mrjj from './learn.js'
重命名为mrjj
导入js文件
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import * as mrjj from './learn.js'
import {content} from './learn.js'
console.log(content);
console.log(mrjj.learner);
mrjj.learn()
</script>
</body>
</html>
export default
导出一个完整的对象 export default
只能有一个export
javascript
export default{
content : "模块化",
learner : "MRJJ_9",
learn()
{
console.log(`${this.learner}在学习${this.content}`);
}
}
import mrjj_lr from './learnDefault.js'
需要取别名才能导入
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import mrjj_lr from './learnDefault.js'
mrjj_lr.learn()
</script>
</body>
</html>
但在浏览器中不能使用
全局注册
javascript
<body>
<div id="aside"></div>
<script type="module">
import {createApp} from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
import Asider from './Asider.js'
import Counter from './Counter.js'
const asideApp=createApp(Asider);
// 全局注册
const asideVM=asideApp.component('Counter',Counter).mount("#aside");
</script>
</body>
局部注册
const asideVM=asideApp.mount("#aside");
先在需要导入其他组件的文件里导入组件
import Counter from './Counter.js';
在export default添加components
export default{
components:{Counter}}