将值传递给 LWC 中的闪电输入标签

liz*_*lav 5 salesforce salesforce-lightning lwc

有谁知道如何将选中的值传递给 Lightning Web 组件中的复选框?

我的代码如下所示:

import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
    @track isChecked;

    constructor() {
        super();
        isChecked = false;
    }   

}
Run Code Online (Sandbox Code Playgroud)
<template>
    <lightning-card title="My Card" icon-name="custom:custom9">
        <div class="slds-m-around_medium">
                <lightning-input type="checkbox" label="my checkbox" name="input1" checked="{isChecked}"></lightning-input>
        </div>
    </lightning-card>    
</template>
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

小智 1

请参考我为你编写的代码,如果不问我,它应该是有意义的。

您的一个或多个复选框的 html

<template>
    For multiple Checkbox use Checkbox Group
    <lightning-checkbox-group name="Checkbox Group"
                              label="Checkbox Group"
                              options={options}
                              value={value}
                              onchange={handleChange}></lightning-checkbox-group>
    <p>Selected Values are: {selectedValues}</p>

      for just single Checkbox
    <input type="checkbox" name="vehicle1" value="Bike" id="mycheck" onclick={myFunction}> I have a bike<br>

    <p>Selected:</p> {checkvalue} 
</template>
Run Code Online (Sandbox Code Playgroud)

你的js来处理这个问题,对于单个复选框,现在它为复选框分配值(你实际要求的)以保持简单,你可以修改它以根据最后一个值分配true false。

import { LightningElement, track } from 'lwc';

export default class CheckboxGroupBasic extends LightningElement {
    @track value = ['option1'];
    @track checkvalue ;

    get options() {
        return [
            { label: 'Ross', value: 'option1' },
            { label: 'Rachel', value: 'option2' },
        ];
    }

    get selectedValues() {
        return this.value.join(',');
    }

    handleChange(e) {
        this.value = e.detail.value;
    }

    myFunction(e){  // it is simple assigning value. here you can toggle value
         this.checkvalue = e.target.value;
    }
}

Run Code Online (Sandbox Code Playgroud)

我们有 LWC Playground 链接,您希望看到它正常工作。 https://developer.salesforce.com/docs/component-library/tools/playground/1_UbRgnJ9/9/edit