使用 sammy.js 重新加载页面

Reload the page using sammy.js

我在 asp.net mvc 中将 sammy.js 用于单页应用程序。
一切都很好,但我遇到了一个问题,就是无法重新加载页面。
例如,当我在仪表盘中时,我的 URL 是

http://localhost:1834/#/Home/Index?lblbreadcum=Dashboard

layout.cshtml

 <script>
    $(function () {

        var routing = new Routing('@Url.Content("~/")', '#page', 'welcome');

        routing.init();

    });
</script>

routing.js

var Routing = function (appRoot, contentSelector, defaultRoute) {

function getUrlFromHash(hash) {

    var url = hash.replace('#/', '');
    if (url === appRoot)
        url = defaultRoute;

    return url;
}

return {

    init: function () {
        Sammy(contentSelector, function () {


            this.get(/\#\/(.*)/, function (context) {
                var url = getUrlFromHash(context.path);

                context.load(url).swap();

            });

        }).run('#/');
    }
};
}

我想通过单击仪表板重新加载页面 menu/link。但是点击事件没有触发,因为 link 没有改变。但是,如果我想转到另一页,那就没问题了。请帮帮我。谢谢

我认为您必须再次附加相同的部分。你不能 "update" 这个意思的部分。 正如您在 post 中所说,当您单击另一个 link 然后再次返回时,它会起作用。

这就是您必须要做的。再次附加相同的 page/partial,通过这样做,您可以清除所有变量并通过模拟刷新重新创建它们。

编辑:添加示例 请注意,我没有直接复制您的代码,但我想您会理解的:) 在我的例子中我没有使用井号 (#)。

var app = Sammy(function () {

        this.get('/', function (context) {
             // context is equalient to data.app in the custom bind example
             // currentComponent('home'); I use components in my code but you should be able to swith to your implementation
            var url = getUrlFromHash(context.path);
            context.load(url).swap();
        });

        this.bind('mycustom-trigger', function (e, data) {
            this.redirect('/'); // force redirect
        });

        this.get('/about', function (evt) {
            // currentComponent('about'); I use components in my code but you should be able to swith to your implementation
            var url = getUrlFromHash(context.path);
            context.load(url).swap();
        });

    }).run();

    // I did an easy example trigger here but I think you will need a trigger on your link-element. Mayby with a conditional check wheter or not to trigger the manually binding or not
    $('.navbar-collapse').click(function () {
        app.trigger('mycustom-trigger', app);
    });

请阅读 sammy.js

中有关 events and routing 的更多信息

祝你好运:)

强制重新加载路由的更简单、更简洁的方法是调用 Sammy.Application refresh() method:

import { sammyApp } from '../mySammyApp';

const url = `${mySearchRoute}/${encodeURIComponent(this.state.searchText)}`;
if (window.location.hash === url) {
    sammyApp.refresh();
else {
    window.location.hash = url;
}