简体   繁体   English

在 Webcomponent/Stencil.js 中显示四种不同的汽车标志

[英]Show four different car logos in Webcomponent/Stencil.js

I am new to Web Components and to Stencil.js and I am working on an application that provides detailled car information regarding on the selection of car type through the user.我是 Web 组件和 Stencil.js 的新手,我正在开发一个应用程序,该应用程序提供有关通过用户选择汽车类型的详细汽车信息。 I need to show four different logos according to the Response from the server, as there are just four images provided for the Logos.我需要根据来自服务器的响应显示四个不同的徽标,因为徽标只提供了四个图像。 My request to the backend works well and my condition on which Logo to render as well;我对后端的请求运行良好,并且我的条件也适用于渲染徽标; I am currently logging this information to the console.我目前正在将此信息记录到控制台。

Now I need to display these four different logos according to the response in the template and that is the problem.现在我需要根据模板中的响应显示这四个不同的徽标,这就是问题所在。 I tried Handlebars-Syntax in the render-Method of the Component, but that didn´t worked and gives me an error.我在组件的 render-Method 中尝试了 Handlebars-Syntax,但没有奏效并给我一个错误。

So I am stuck here and searching for a solution.所以我被困在这里并寻找解决方案。 I couldn´t find any until now on Google or here.直到现在我在谷歌或这里都找不到任何东西。

I created the checkLogo method in order to get the Logos rendered according to the response of the backend.我创建了 checkLogo 方法,以便根据后端的响应获取呈现的徽标。

In the render() method, I created four Handlebars-like if-conditions, that are not working and giving an error.在 render() 方法中,我创建了四个类似 Handlebars 的 if 条件,它们不起作用并给出错误。

The images should be rendered from the image source folder weather it´sa bmw, mercedes, volkswagen or audi.图像应从图像源文件夹天气它是宝马、梅赛德斯、大众或奥迪渲染。

Any hints or help would be very much appreciated, thanks!任何提示或帮助将不胜感激,谢谢!

The code is the following:代码如下:

import {Component, Event, EventEmitter, h, Method, Prop, State} from '@stencil/core';
import {Icon} from '../../utils/utils';
import {xxxCarsearchResultModel} from './xxx-carsearch-result.model';






function checkLogo(response) {
    for (var key in response) {
        // skip loop if the property is from prototype
        if (!response.hasOwnProperty(key)) continue


            var obj = response[key];
            for (var prop in obj) {
                // skip loop if the property is from prototype
                if (!obj.hasOwnProperty(prop)) continue;
                // iterating through the nested objects
                console.log(prop + " = " + obj[prop]);
            }
            var parsed = (obj[prop]);
            // if (parsed == 'Audi'  || parsed == 'BMW' ||  parsed == 'Volkswagen' || parsed == 'Mercedes'  ) {
            //     console.log('it is an ' + obj[prop]);
            //
            //
            // }
            // else console.log('it´s another car')




    }

}

@Component({
    tag: 'xxx-carsearch',
    styleUrl: 'xxx-carsearch.scss',
    shadow: true
})
export class CarSearch {
    /**
     * The score
     */
    @Prop({mutable: true, reflectToAttr: true}) tsn: string = null;
    @Prop({mutable: true, reflectToAttr: true}) hsn: number = null;

    @Event() carSelected: EventEmitter<VhvCarsearchResultModel>;

    @State() page = 1;
    @State() wsresult: [];

    brand: string;
    model: string;
    fuel: string;
    type: string;
    power: string;
    variant: string;

    selectedcar: string;
    apiPath = 'https://test.xxx.de/xxxx/api/v1/car/guided';

    @Method()
    async getTsn() {
        return this.tsn;
    }

    @Method()
    async getHsn() {
        return this.hsn;
    }

    componentWillLoad() {
        return this.loadWS(this.apiPath);
    }


    loadWS(url: RequestInfo) {
        return fetch(url)
            .then((response: Response) => response.json())
            .then((response) => {
                this.wsresult = response;

            });
    }


    render() {
        let title;
        if (this.page === 1) {
            title = 'Ihr Fahrzeughersteller';
        } else if (this.page === 2) {
            title = 'Modell';
        } else if (this.page === 3) {
            title = 'Kraftstoff';
        } else if (this.page === 4) {
            title = 'Fahrzeugkategorie';
        } else if (this.page === 5) {
            title = 'Leistung';
        } else if (this.page === 6) {
            title = 'Bitte wählen Sie Ihr Fahrzeug';
        }

        if (this.page === 5) {
            return (
                <div>
                    <vhv-icon class='backbutton' onClick={() => this.pageBack()}
                              icon={Icon.Left}/>
                    <h1>{title}</h1>

                    <div class='listwrapper'>
                        {
                            this.wsresult.sort((a: any, b: any) => a.horsePowerFrom - b.horsePowerFrom).map(((element: any) =>
                                    <div class='listelement' onClick={() => this.nextStep(element.key)}>
                                        {element.horsePowerFrom}-{element.horsePowerTo} PS
                                        <vhv-icon size={25} icon={Icon.Right}/>
                                    </div>
                            ))
                        }
                    </div>
                </div>
            );
        } else if (this.page === 6) {
            return (
                <div>
                    <vhv-icon class='backbutton' onClick={() => this.pageBack()}
                              icon={Icon.Left}/>
                    <h1>{title}</h1>
                    <div class='listwrapper'>
                        {
                            this.wsresult.sort((a: any, b: any) => a.horsePowerFrom - b.horsePowerFrom).map(((element: any) =>
                                    <div class='listelement'
                                         onClick={() => this.setTsnHsn(element.tsn, element.hsn, element.brand, element.modelDetailed)}>
                                        {element.modelComplete} HSN: {element.hsn} TSN: {element.tsn}
                                        <vhv-icon size={25} icon={Icon.Right}/>
                                    </div>
                            ))
                        }
                    </div>
                </div>
            );
        } else if (this.page === 7) {
            return (
                <div class='fertig'>
                    <div class='fertigwrapper'>
                        <img src='https://www.xxx.de/xxxxx/auto/bmw@2x.fdc06cc429d06c8c96fc.png'/>
                        {this.selectedcar}
                    </div>
                    <vhv-button onClick={() => this.reset()} icon={Icon.Check}>Neue Suche</vhv-button>
                </div>
            );
        } else {
            return (
                <div>
                    {/*<vhv-icon class='backbutton' hidden={this.page === 1} onClick={() => this.pageBack()}
                              icon={Icon.Left}/>*/}
                    <h1>{title}</h1>
                    <div class="vhv-cs-front">
                        <vhv-search  placeholder="Hersteller suchen..."></vhv-search>
                    </div>
                    <div class='list_wrapper'>
                        <div class='listwrapper top'>
                            <div class='listelement top'>
                                <h4> Häufig gewählte Hersteller</h4>
                            </div>
                            {
                                this.wsresult.slice(0,7).sort((a: any, b: any) => a.value.localeCompare(b.value)).map(((element: any) =>
                                        <div class='listelement' onClick={() => this.nextStep(element.key)}>

                                            <img hidden={this.page !== 1}
                                                 {{#if parsed '==' audi}}
                                                 src='/assets/logos/audi.png'/>
                                            {element.value}
                                            <vhv-icon size={25} icon={Icon.Right}/>
                                            <img hidden={this.page !== 1}
                                                 {{#if parsed '==' 'bmw'}}
                                                 src='/assets/logos/bmw.png'/>
                                            {element.value}
                                            <vhv-icon size={25} icon={Icon.Right}/>
                                            <img hidden={this.page !== 1}
                                                 {{#if parsed '==' 'mercedes'}}
                                                 src='/assets/logos/mercedes.png'/>
                                            {element.value}
                                            <vhv-icon size={25} icon={Icon.Right}/>

                                            <img hidden={this.page !== 1}
                                                 {{#if parsed '==' 'volkswagen'}}
                                                 src='/assets/logos/volkswagen-vw.png'/>
                                            {element.value}
                                            <vhv-icon size={25} icon={Icon.Right}/>
                                        </div>
                                ))
                            }
                        </div>
                        <div class='listwrapper'>
                            <div class='listelement top'>
                                <h4>Alle Hersteller</h4>
                            </div>
                            {
                                this.wsresult.sort((a: any, b: any) => a.value.localeCompare(b.value)).map(((element: any) =>
                                        <div class='listelement' onClick={() => this.nextStep(element.key)}>

                                            <img hidden={this.page !== 1}
                                                 src='/assets/logos/audi.png'/>
                                            {element.value}
                                            <vhv-icon size={25} icon={Icon.Right}/>
                                        </div>
                                ))
                            }
                        </div>
                    </div>
                </div>
            );
        }
    }

    nextStep(value: string) {
        if (this.page === 1) {
            this.loadWS(this.apiPath + '?brand=' + value).then(() => {
                this.brand = value;
                this.page = 2;
            });
        } else if (this.page === 2) {
            this.loadWS(this.apiPath + '?brand=' + this.brand + '&model=' + value).then(() => {
                this.model = value;
                this.page = 3;
            });
        } else if (this.page === 3) {
            this.loadWS(this.apiPath + '?brand=' + this.brand + '&model=' + this.model + '&fuel=' + value).then(() => {
                this.fuel = value;
                this.page = 4;
            });
        } else if (this.page === 4) {
            this.loadWS(
                this.apiPath + '?brand=' + this.brand + '&model=' + this.model + '&fuel=' + this.fuel + '&variant=' + value).then(() => {
                this.variant = value;
                this.page = 5;
            });
        } else if (this.page === 5) {
            const url = `${this.apiPath}?brand=${this.brand}&model=${this.model}&fuel=${this.fuel}&variant=${this.variant}&power=${value}`;
            this.loadWS(url).then(() => {
                this.power = value;
                this.page = 6;
            });
        }
    }

    pageBack() {
        this.page--;
        if (this.page === 1) {
            return this.componentWillLoad();
        } else if (this.page === 2) {
            return this.loadWS(this.apiPath + '?brand=' + this.brand);
        } else if (this.page === 3) {
            return this.loadWS(this.apiPath + '?brand=' + this.brand + '&model=' + this.model);
        } else if (this.page === 4) {
            return this.loadWS(this.apiPath + '?brand=' + this.brand + '&model=' + this.model + '&fuel=' + this.fuel);
        } else if (this.page === 5) {
            return this.loadWS(`${this.apiPath}?brand=${this.brand}&model=${this.model}&fuel=${this.fuel}&variant=${this.variant}`);
        }
    }

    setTsnHsn(tsn: string, hsn: number, brand: string, model: string) {
        this.tsn = tsn;
        this.hsn = hsn;
        this.selectedcar = brand + ' ' + model;
        this.page = 7;

        this.carSelected.emit({
            hsn: this.hsn,
            tsn: this.tsn
        });
    }

    reset() {
        this.page = 1;
        this.tsn = null;
        this.hsn = null;
        return this.componentWillLoad();
    }
}

You can't directly use if statements in JSX like that, but you could use a ternary operator :你不能像这样在 JSX 中直接使用if语句,但你可以使用三元运算符

render() {
  return (<img src={condition === 1 ? 'img1.png' : 'otherImg.png'} />);
}

This is more suitable for cases where you only have two options as it can become difficult to read.这更适合您只有两个选项的情况,因为它可能会变得难以阅读。 If you have more options you can do:如果您有更多选择,您可以执行以下操作:

render() {
  return (<div>
    {condition === 1 && (<img src="img1.png" />)}
    {condition === 2 && (<img src="img2.png" />)}
    {condition === 3 && (<img src="img3.png" />)}
  </div>);
}

This will only render img tags where the condition is true .这只会在条件为true的情况下呈现img标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM