【问题标题】:How can I send init data to a Mithril component如何将初始化数据发送到 Mithril 组件
【发布时间】:2018-09-09 04:59:07
【问题描述】:

我正在尝试通过将 ID 设置为从服务器获取数据来初始化 Mithril 组件,如下所示:

// view/UserList.js
module.exports = {
    oninit: function(vnode) {
        console.log(vnode);
        var groupId = vnode.attrs.groupId;
        console.log('The group ID is '+groupId);
        User.loadUsersInGroup(groupId);
    },
    view: ...
}

我有以下:

var userList = require('./view/UserList');
m.mount(document.body, UserList, {groupId: 5});

但我明白了:

vnode.attrs is undefined

我尝试将其更改为:

var UserList = require('./view/UserList');
m.mount(document.body, m(UserList, {groupId: 5}));

但现在我明白了:

m.mount(element, component) expects a component, not a vnode

如何正确填充 vnode.attrs?

【问题讨论】:

    标签: mithril.js


    【解决方案1】:

    向组件发送初始化数据的正确方法可以在https://mithril.js.org/mount.html#description找到。

    要在安装组件时传递参数,请使用:

    m.mount(element, {view: function () {return m(Component, attrs)}})
    

    所以应用到这个案例中,应该是:

    m.mount(document.body, {view: function() { return m(UserList, {groupId: 5}); }});
    

    其他一些方法是:

    const full   = {view: vnode => m('h1', vnode.attrs.test)}
    const short  = {view: v => m('h1', v.attrs.test)}
    const dest   = {view: ({attrs}) => m('h1', attrs.test)}
    const destf  = {view: ({attrs: {test}}) => m('h1', test)}
    
    m.mount(document.body, {
      view: () => [
        m(full,  {test: "full"}),
        m(short, {test: "short"}),
        m(dest,  {test: "destructured"}),
        m(destf, {test: "fully destructured"})
      ]
    })
    

    See them in action here.(由 Mithril.js Gitter 聊天中的 osban 提供)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2019-01-24
      • 2015-07-24
      • 2017-03-05
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多