Require的基本使用
Require的使用
通过一个简单的小案例 实现数据的调用和注入。
1、整体架构概览
2、功能概述
2.1 代码设计思路
- 如布局图式完成布局
- 导入相关jar包并引入index.html中
- 书写配置文件main.js
- 书写data.js和view.js
- 在index.js中完成调用
2.2 相关实现代码
2.2.1 页面index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script data-main="js/main.js" src="js/lib/require.js"></script>
</head>
<body>
<div class="root">
</div>
</body>
</html>
2.2.2 配置文件mian.js
requirejs.config({
baseUrl:"js/",
paths:{
"jquery":"lib/jquery-3.2.1",
"data":"app/data",
"index":"app/index",
"view":"app/view"
}
//注意:该处是以swiper为例,处理那些未使用define()定义的从外引入的jar
// 为那些没有使用define()来声明依赖关系、设置
// 模块的"浏览器全局变量注入"型脚本做依赖和导出配置
/*shim:{
"swiper":{
deps:["jquery"],
exports:"swiper"
}
}*/
})
requirejs(["jquery","data","index","view"],function($,data,index,view){
})
2.2.3 数据文件data.js和view.js
define(function(){
return{
data:"Hello Require!"
}
})
define(["jquery"],function($){
// 获取视图
/*
set和get
set:设置
get:获取
*/
function getView(){
return $(".root");
}
function setView(data){
getView().html(data);
}
return {
setView:setView
}
})
2.2.4 书写index.js
define(["data","view"],function(data,view){
view.setView(data.data);
})