如何使用 x-init 使用 AlpineJS 设置下拉选项的“selected”属性

dwk*_*kns 2 javascript alpine.js

我有一个使用 AlpineJS 提交的表单。

使用x-init我想使用从 cookie 读取的两个字母字符串将下拉列表默认为特定国家/地区。

如何使用我输入的 2 个字母代码initForm()来设置selected下拉列表的属性?

<div x-data="marketingForm()" x-init="initForm()">
  <form id="formID-Contact" name="Contact" data-pageurl="http://localhost:8080/form-test/" class="">
    <div>
      <label for="country" >Country / Region</label>
      <select id="country" name="country" autocomplete="country">
        <option value='GB'>United Kingdom</option>
        <option value='US'>United States</option>
        <option value='CA'>Canada</option>
        <option value='MX'>Mexico</option>
      </select>
    </div>
    <a>
      <button @click.prevent=submitMarketingForm() id='formSubmitButton'>submit</button>
    </a>
  </form>
</div>
Run Code Online (Sandbox Code Playgroud)

还有JS

window.marketingForm = () => {
  return {
    detectedCountry: '',
    initForm() {
      let country = getCountry() // function that reads a cookie and returns 2 letter code eg. UK. 
      this.detectedCountry = country // how do I use this to set selected attribute of relevant option
      
    },
    submitMarketingForm(formID) {
      // Do the form submitting stuff
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以假设detectedCountry设置为 UK 我想最终得到:

<select id="country" name="country" autocomplete="country">
  <option selected value='GB'>United Kingdom</option>
  <option value='US'>United States</option>
  <option value='CA'>Canada</option>
  <option value='MX'>Mexico</option>
</select>
Run Code Online (Sandbox Code Playgroud)

NIC*_*ICO 8

如果国家/地区的键等于检测到的国家/地区,则只需绑定选定的属性即可。我建议将国家/地区存储在您的数据对象中。

<div x-data="marketingForm()" x-init="initForm()">
  <form id="formID-Contact" name="Contact" data-pageurl="http://localhost:8080/form-test/" class="">
    <div>
      <label for="country" >Country / Region</label>
      <select id="country" name="country" autocomplete="country">
        <template x-for="country in countries">
          <option 
            :value='country.key'
            :selected="country.key === detectedCountry"
            x-text="country.name"
          >
          </option>
        </template>
      </select>
    </div>
    <a>
      <button @click.prevent=submitMarketingForm() id='formSubmitButton'>submit</button>
    </a>
  </form>
</div>


<script>
const marketingForm = () => {
  return {
    countries: [
      { key: 'GB', name: 'United Kingdom' },
      { key: 'US', name: 'United States' },
      { key: 'CA', name: 'Canada' },
      { key: 'MX', name: 'Mexico' },
    ],
    detectedCountry: '',
    initForm() {
      let country = 'GB' // function that reads a cookie and returns 2 letter code eg. UK. 
      this.detectedCountry = country // how do I use this to set selected attribute of relevant option
      
    },
    submitMarketingForm(formID) {
      // Do the form submitting stuff
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)