How i can do imports in F7 routed component?

Hi!
I need help about do imports in a routed component, the main doubt is, where i can put my import statements?

For example:

If I have a component that looks something like this:
{ path: 'routed-component', component: { template: '...', style: '...', data: function()...., methodss: {...}, on: {...} } }

Where should i place my import statements?

Don’t clear what you are trying to achieve? Can you show example of what and where do you need to import?

Shure! Thanks for reply!!

If i have a F7 component that looks like this:
image

And i need to move it to a routed component, or something like:

File routes.js
{ ... other routes, { path: "/example-route-component/", component: { template: {"......the html template"}, data: ...... methods: .... } }
Where should i place my `import {lib} from “some-lib”?

Hi, try at the head of routes.js

import {lib} from 'some-lib'
...
{
  path: 'my-route',
  component: {
    template: {...},
    data:{...},
    methods: {
      myMethod () {
        let result = lib(foo)
      }
    }
  }
}

Hi, thanks for your response! That works, but, it is not what i need. Your solution is not the best way because that implicates load all my libs in routes probably when i still don’t need them.
I’m searching the way to load the lib when the component route is loading.

i try a small test in one app and gave me a syntax error, using webpack:

Syntax Error: SyntaxError: path\routes.js: 'import' and 'export' may
only appear at the top level (30:6)

so i dont think it would be posible. but maybe there is a way.

Use dynamic imports and async route:

{
  path: '/something/',
  async(to, from, resolve) {
    import('some-page-component.f7.html').then((module)=>{
      resolve({
        component: module.default,
      })
    })
  }
}
1 Like

But this not apply for my question, it that you mentioned, as far as i understand, is for load the component if it is in a .f7.html file, but i don’t have that, instead i have a component like this in that route component: { template: {...}, data:{...}, methods: { myMethod () { alert(1); } } }
If i wrong, can You provide an example using a library import (not component)?

What is the component in route component? Check the import docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import it works for all kind of js modules

I have this f7.html file and i need to convert this to route component :confused:

<div class="page" data-name="login">
    <div class="page-content" style="width: 60%;margin-left : 20%">
        <form class="list" id="form-login">
            <div style="margin-left: 30%">
                <img id="companyImg" src="{{ companyImage }}" alt="Company Image" style="width: 60%;height:auto;" />
            </div>

            <div class="list no-hairlines-md">
                <ul>
                    <li>
                        <div class="item-content item-input">
                            <div class="item-inner">
                                <div class="item-title item-label">
                                    Usuario:
                                </div>
                                <div class="item-input-wrap">
                                    <input type="text" name="userLogin" placeholder="Ingrese su usuario." required
                                        validate />
                                    <span class="input-clear-button"></span>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-content item-input item-input-with-info">
                            <div class="item-inner">
                                <div class="item-title item-label">
                                    Contraseña:
                                </div>
                                <div class="item-input-wrap">
                                    <input type="password" @keyup="pressEnter($event)" name="password"
                                        placeholder="Ingrese su contraseña." required validate />
                                    <span class="input-clear-button"></span>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </form>
        <div class="list inline-labels no-hairlines-md block">
            <button class="col button button-fill color-blue" href="#" @click="userWantsToLogin">
                Ingresar
            </button>
            <br />
            <button class="col button button-fill color-red" href="#">
                Olvide mi contraseña
            </button>

            <div class="item-input-outline">
                <p class="item-input-wrap text-align-center">
                    {{ lastLogin }} / {{ lastLoginDate }}
                </p>
            </div>
            <p class="text-align-center" style="font-weight: bold">
                Retail for NAV
            </p>
        </div>
    </div>
</div>
import {
    Credential
} from "../ts/entities/credential";
import XConnectService from "../js/xconnect/Service/XConnectService";

import {
    Source,
    TypeConnection
} from "../js/xconnect/EnumAndType/XConnectType";
import {
    UserInteractionService
} from "../ts/services/user-interaction";
import {
    Utilities
} from "../ts/utils/utils.ts";
import {
    AppService
} from "../ts/services/app.ts";
import {
    TemplateLoaderService
} from "../ts/services/template-loader";

import {
    enums
} from "../ts/enum/enum.ts";

var userInteraction = UserInteractionService.getInstance();
var xConnectServiceInstance = XConnectService.getInstance();

export default {
    data: function () {
        return {
            title: "Configuración",
            lastLogin: "",
            lastLoginDate: null
        };
    },
    methods: {
        userWantsToLogin: async function () {
            userInteraction.showPreloader();
            var securityService = SecurityService.getInstance();

            var appService = AppService.getInstance();
            var appInstance = appService.appInstance;
            try {
                var formData = appInstance.form.convertToData(
                    "#form-login"
                );
                var credential = Credential.createCredentials(
                    formData.userLogin,
                    formData.password,
                    "RETAILFORNAV",
                    null
                );
                var result = await securityService.loginUser(credential);
                credential.communicationAddress =
                    result.CommunicationAddress;
                xConnectServiceInstance.setUrl(result.CommunicationAddress);
                appService.setLocalValue(
                    "UserCredentials",
                    Utilities.serialize(credential)
                );
                try {
                    xConnectServiceInstance.getCollection(
                        enums.operationCodes.getUser, {
                            UserLogin: credential.loginId
                        },
                        Source.Server,
                        TypeConnection.Api,
                        data => {
                            let credentials = Utilities.deserialize(
                                appService.getLocalValue("UserCredentials")
                            );
                            let object =
                                data.collectionResult[0].collection[0];
                            appService.setLocalValue(
                                "LastLoginUser",
                                credential.loginId
                            );
                            var loggedDate = new Date();
                            var strLoggedDate =
                                loggedDate.getDate() +
                                "-" +
                                (loggedDate.getMonth() + 1) +
                                "-" +
                                loggedDate.getFullYear() +
                                " " +
                                loggedDate.getHours() +
                                ":" +
                                loggedDate.getMinutes() +
                                ":" +
                                loggedDate.getSeconds();
                            appService.setLocalValue(
                                "LastLoginDate",
                                strLoggedDate
                            );
                            appService.setLocalValue(
                                "CompanyImage",
                                object.Image
                            );
                            appService.setLocalValue("SalePointId", object.SalePoint);
                            credential.UserInfo = object;
                            this.loadTemplates(credential.loginId);
                        },
                        error => {
                            userInteraction.showError(error);
                        }
                    );
                } catch (error) {
                    userInteraction.showError(error);
                }
            } catch (error) {
                userInteraction.showError(error);
            }
        },
        loadTemplates: function (userLogin) {
            try {
                var appService = AppService.getInstance();
                var appInstance = appService.appInstance;
                xConnectServiceInstance.getCollection(
                    enums.operationCodes.getNavigationObject, {
                        UserLogin: userLogin
                    },
                    Source.Server,
                    TypeConnection.Api,
                    data => {
                        if (
                            !data ||
                            !data.collectionResult ||
                            data.collectionResult.lenght <= 0
                        ) {
                            throw new Error(
                                "Usuario sin opciones de navegación configuradas, por favor, comuníquese con su administrador."
                            );
                        }
                        this.loadParameters();
                        TemplateLoaderService.getInstance().prepareMenu.next(
                            data.collectionResult[0].collection
                        );

                        //  TODO: Use it for switch to main view when all the templates are loaded
                        // appInstance.views.main.router.navigate("/form/", {
                        //     reloadCurrent: true
                        // });
                    },
                    error => {
                        userInteraction.showError(error);
                    }
                );
            } catch (error) {
                userInteraction.showError(error);
            }
        },
        loadParameters: function () {
            try {
                var appService = AppService.getInstance();
                xConnectServiceInstance.getCollection(
                    enums.operationCodes.getParameters, {},
                    Source.Server,
                    TypeConnection.Api,
                    data => {
                        if (
                            !data ||
                            !data.collectionResult ||
                            data.collectionResult.lenght <= 0 ||
                            data.collectionResult[0].collection.lenght <= 0
                        ) {
                            throw new Error(
                                "Parametros de sistema no configurados, consulte a su administrador."
                            );
                        }
                        let parameters = data.collectionResult[0].collection;
                        let paramCurrency = parameters.find(param => {
                            return param.Name == enums.paramNames.currency;
                        });
                        let paramLocalString = parameters.find(param => {
                            return param.Name == enums.paramNames.regionalInfoCode;
                        });
                        let paramMinimumFractionDigits = parameters.find(param => {
                            return param.Name == enums.paramNames.minimumFractionDigits;
                        });
                        if (paramCurrency) {
                            appService.setCurrency(paramCurrency.Value);
                        } else {
                            throw new Error(
                                "El parámetro de moneda no ha sido configurado"
                            );
                        }
                        if (paramLocalString) {
                            appService.setRegionalInfoCode(paramLocalString.Value);
                        } else {
                            throw new Error(
                                "El parámetro del codigo de información regional no ha sido configurado"
                            );
                        }
                        if (paramMinimumFractionDigits) {
                            appService.setMinimumFractionDigits(paramMinimumFractionDigits.Value);
                        } else {
                            throw new Error(
                                "El parámetro de la cantidad mínima de decimales no ha sido configurado"
                            );
                        }
                    },
                    error => {
                        userInteraction.showError(error);
                    }
                );
            } catch (error) {
                userInteraction.showError(error);
            }
        },
        pressEnter: function ($event) {
            var appService = AppService.getInstance();
            var formLogin = appService.appInstance.form.convertToData(
                "#form-login"
            );
            if (event.keyCode == 13) {
                if (formLogin.userLogin == "") {
                    userInteraction.showError("Ingrese su usuario.");
                } else {
                    if (formLogin.password == "") {
                        userInteraction.showError("Ingrese su contraseña.");
                    } else {
                        this.userWantsToLogin();
                    }
                }
            }
        }
    },
    on: {
        pageInit: function (e, page) {
            // do something on page init

            var appService = AppService.getInstance();
            var lastLogin = appService.getLocalValue("LastLoginUser");
            var lastLoginDate = appService.getLocalValue("LastLoginDate");
            var companyImage = appService.getLocalValue("CompanyImage");
            var formDataObject = null;
            if (!lastLogin) {
                lastLogin = "Último usuario";
            } else {
                formDataObject = {
                    userLogin: lastLogin
                };
            }
            if (!lastLoginDate) {
                lastLoginDate = "Último inicio de sesión";
            }
            this.$setState({
                lastLogin: lastLogin,
                lastLoginDate: lastLoginDate,
                hasCompany: this.hasCompany
            });
            if (formDataObject) {
                appService.appInstance.form.fillFromData(
                    "#form-login",
                    formDataObject
                );
            }
            appService.appInstance
                .$("#companyImg")
                .attr("src", companyImage);
        }
    }
};

Then i need to convert the previous component to the form:

{
path: ‘/some-page/’,
// Component Object
component: {
template: <div class="page"> <div class="navbar"> <div class="navbar-inner"> <div class="title">{{title}}</div> </div> </div> <div class="page-content"> <a @click="openAlert" class="red-link">Open Alert</a> <div class="list simple-list"> <ul> {{#each names}} <li>{{this}}</li> {{/each}} </ul> </div> </div> </div>,
style: .red-link { color: red; },
data: function () {
return {
title: ‘Component Page’,
names: [‘John’, ‘Vladimir’, ‘Timo’],
}
},
methods: {
openAlert: function () {
var self = this;
self.$app.dialog.alert(‘Hello world!’);
},
},
on: {
pageInit: function (e, page) {
// do something on page init
},
pageAfterOut: function (e, page) {
// page has left the view
},
}
},
}

like you show in your documentation.
Component Structure

So the main question is, where should i place the import statements in something like the above structure?

try like this,

routes = [
  ...
  {
    path: '/some-page/',
    componentUrl: './some-page.html',
  },
  ..
];

and the component (some-page.html)

<!-- component template -->
<template>
  <div class="page">
    ...
  </div>
</template>
<!-- component styles -->
<style>
  .red-link {
    color: red;
  }
</style>
<!-- rest of component data and methods -->
<script>
import {foo} from 'bar'
  return {
    data: function () {
      return {
        title: 'Component Page',
        names: ['John', 'Vladimir', 'Timo'],
      }
    },
    methods: {
      openAlert: function () {
        var self = this.$app.dialog.alert('Hello world!');
      },
    },
    on: {
      pageInit: function () {
        // do something on page init
      },
      pageAfterOut: function () {
        // page has left the view
      },
    }
  }
</script>

Thanks @pvtallulah !! That works well, however, I need to change something like what you mentioned in a structure like this:

and this is where i don’t know where should i put the import statements.

why do you need to change that way? what are you trying to achive?

i dont know another way of importing just a single export, unless you make the import on the file head. but you dont want to bcs you have a lot of imports, im assuming.

I need that because I want to load the template dynamically when the application is loading, I was looking for information about my problem but no solution was found.
Thanks for your time @pvtallulah

Sorry, still dont understand what you need. My native language is spanish.
So you want to “preload” the component while the app is loading?

Really? Taht’s good, mine too!!!
Exactamente lo que necesito es precargar el componente cuando se cargue la aplicacion!!

Ok, podes probar con keepAlive.
no hace exactamente lo que necesitas. Pero voy a ver si encuentro otra forma de cargar el componente.

https://framework7.io/docs/routes.html#keep-alive

Pregunto de curioso nomas, poruqe necesitas percargar el componente?

Lo que sucede es que los COMPONENTES van a venir desde otro lado, por medio de una API REST al momento de que el usuario inicie sesion, se obtendran sus COMPONENTES ASOCIADOS y se van a precargar con Template7.

nunca implemente algo asi, por ahi podrias considerar usar SSR.