「前端」超好用的 MithrilJS 教程之核心概览

MithrilJS

有关 Mithril.js 的基础教程请看我的这篇文章:易、轻、快!超牛逼纯JS前端框架——MithrilJS

个人认为这个框架不就可能会火,这才是 JS 意义上的面向对象编程,兼容到 IE9,还是非常不错的。

入门教程已经写过,这边就根据官网的英文文档结合实例来进行更加全面的解析,放宽心,这个框架简单的一塌糊涂,不信你对比下 Angular,你就知道 Angular 有多复杂了(对象是纯前端工程师,不是你们这帮后端工程化大拿),当然,React 与 Vue 都一样,没有对比就没有伤害。


概览

m(selector, attrs, children)

核心函数,用来从虚拟 DOM 生成真实 DOM 的关键。

m("div.class#id", {title: "title"}, ["children"])

m.mount(element, component)

自动 diff DOM 结构树,从而达到数据驱动作用,就是数据变化 DOM 自动更新啦。

var state = {

count: 0,

inc: function() {state.count++}

}

var Counter = {

view: function() {

return m("div", {: state.inc}, state.count)

}

}

m.mount(document.body, Counter)

m.route(root, defaultRoute, routes)

路由,用来设置路由跳转。

var Home = {

view: function() {

return "Welcome"

}

}

m.route(document.body, "/home", {

"/home": Home, // defines `http://localhost/#!/home`

})

m.route.set(path)

函数式路由调转,就是不使用 a 标签,使用事件触发跳转,类比 location.href 即可。

m.route.set("/home")

m.route.get()

获取当前路由,可以用来解析数据等。

var currentRoute = m.route.get()

m.route.prefix(prefix)

设置路由之前使用,用来配置路由的前缀,比如默认是:#!,可以修改为 # 等等。

m.route.prefix("#!")

m.route.link()

给 a 标签设置的东西,让 MithrilJS 知道这个 a 标签是路由,不是页面跳转,可以省略路由前缀。

m("a[href='/Home']", {oncreate: m.route.link}, "Go to home page")

m.request(options)

MithrilJS 的 Ajax 了。

m.request({

method: "PUT",

url: "/api/v1/users/:id",

data: {id: 1, name: "test"}

})

.then(function(result) {

console.log(result)

})

m.jsonp(options)

jsonp,本人认知就在跨域了,没用过,我后面的教程也会过滤掉这里的内容。

m.jsonp({

url: "/api/v1/users/:id",

data: {id: 1},

callbackKey: "callback",

})

.then(function(result) {

console.log(result)

})

m.parseQueryString(querystring)

解析 query 传参到对象。

var object = m.parseQueryString("a=1&b=2")

// {a: "1", b: "2"}

m.buildQueryString(object)

与上面相反,把对象解析为 query 字符串。

var querystring = m.buildQueryString({a: "1", b: "2"})

// "a=1&b=2"

m.withAttr(attrName, callback)

input 等输入表单标签双向绑定工具。

var state = {

value: "",

setValue: function(v) {state.value = v}

}

var Component = {

view: function() {

return m("input", {

oninput: m.withAttr("value", state.setValue),

value: state.value,

})

}

}

m.mount(document.body, Component)

m.trust(htmlString)

直接插入 html 标签函数,如无必要,慎用,较危险。

m.render(document.body, m.trust("

Hello

"))

m.redraw()

手动重新渲染,使用 m.mount 与 m.route 目前还没用到过。

var count = 0

function inc() {

setInterval(function() {

count++

m.redraw()

}, 1000)

}

var Counter = {

oninit: inc,

view: function() {

return m("div", count)

}

}

m.mount(document.body, Counter)


差不多久这些函数与功能就涵盖了整个 MithrilJS 了,没错,就这些!

什么 JSX, ES6 等啦,这些归类到插件,使用 webpack 自己配置即可,与 MithrilJS 无关。就像 Vue 也可以不配置 webpack 或不使用 vue-cli,直接使用 CDN 模式开发一样。

个人强烈推荐使用原生模式来练手这个东西,真的,真的,非常好用。甚至你愿意,也可以去扒拉源码看看,一样简单的令你发指!

后面翻译(严格来说是整理)工程量还是有点的,幸好是简单的,不然一个人玩不来。所以会分几期弄完,希望喜欢的人留意下。

喜欢的话,请关注一波,定期更新技术文章,满满的都是干货。


分享到:


相關文章: