面试题答案
一键面试- 创建可复用的组件模块:
- 假设我们要创建一个简单的
button
组件模块。首先创建一个button.js
文件。 - 在ES6模块系统中,可以使用
export
关键字来暴露模块的功能。
// button.js const Button = { render() { return `<button>Click me</button>`; } }; export default Button;
- 假设我们要创建一个简单的
- 实现组件之间的依赖管理:
- 例如,我们有一个
app.js
文件,它依赖于上面创建的button
组件。 - 使用
import
关键字引入依赖的模块。
// app.js import Button from './button.js'; const appDiv = document.createElement('div'); appDiv.innerHTML = Button.render(); document.body.appendChild(appDiv);
- 如果一个模块有多个导出,可以使用命名导出和导入。例如,我们修改
button.js
为:
// button.js const buttonText = 'Click me'; const render = () => `<button>${buttonText}</button>`; export {buttonText, render};
- 在
app.js
中导入时:
// app.js import {render} from './button.js'; const appDiv = document.createElement('div'); appDiv.innerHTML = render(); document.body.appendChild(appDiv);
- 例如,我们有一个