我想创建一个简单的Tab
,但我觉得我的使用很奇怪:
var root = document.body
var index = {
view: () => index.html,
html: m('div', { id: 'div1' }, [
[
(function () {
let value = ["A", "B", "C", "D"]
let output = []
for (let i = 0; i < 4; i++) {
output.push(m('input', {
class: (function () {
if (i == 0) return "onit"
})(),
type: 'button',
value: value[i],
onclick: function () {
let div1 = document.getElementById("div1")
let btn = div1.getElementsByTagName("input")
let div1_div = div1.getElementsByTagName("div")
let _this = this
let num = (function () {
for (let i = 0; i < btn.length; i++) {
if (btn[i] == _this) {
return i
}
}
})()
for (let i = 0; i < btn.length; i++) {
btn[i].className = ""
}
this.className = "onit"
for (let i = 0; i < div1_div.length; i++) {
div1_div[i].setAttribute("style", "dispaly:none")
}
div1_div[num].setAttribute("style", "display:block")
}
}))
}
return output
})()
],
[
(function () {
let arr = ["aaa", "bbb", "ccc", "ddd"]
let output = []
for (let i = 0; i < 4; i++) {
output.push(m("div", { style: (the => i == 0 ? "display:block" : undefined)() }, arr[i]))
}
return output
})()
]
])
}
m.route(root, "/index", {
"/index": index
})
&#13;
答案 0 :(得分:0)
在mithril.js视图中,你只能使用表达式,for
- 循环,if
等等都不是表达式,只能按照你的方式进行。不过还有其他方法可以实现这个目标
使用功能对应物
可以实现循环let values = ["A", "B", "C", "D"]
let output = []
function(){
for (let i = 0; i < 4; i++) {
output.push(m('span', value)
}
return output
}()
可以写成
values.map(value => m('span', value)
if
- 可以使用三元表达式
function() {
if (condition) {
return 'this'
} else {
return 'that'
}
}()
只需使用
condition ? 'this' : 'that'
如果你的视图代码深入嵌套并且你需要自定义逻辑,你也可以使用视图函数:
function someOtherView(someData) {
if (someData.shouldBeShown) {
return someData.text
}
}
function someView() {
...
someOtherView(someData)
...
}
这也使您的观点更具可读性。