【问题标题】:Alpinejs: change values inside children from parent elementAlpinejs:从父元素更改子元素内部的值
【发布时间】:2022-12-09 17:03:59
【问题描述】:

我有一些 alpinejs 的嵌套自定义选择菜单:

<template x-for="(attribute, rootindex) in attributes">
    <div x-ref="attribute.name"
     x-data="{open: false, selectedIndex: false, activeIndex: null, selectedItem:false, items:[...], placeholder:'Choose '+attribute.label }"
     class="my-5">
     ...

你可以看到每个孩子都有自己的状态/变量,如 open、selectedIndex、selectedItem、... 在我想设置其中一些状态的情况下:

我尝试在孩子身上使用 x-ref 但它不起作用,它会返回未定义的! 此功能在父级:

    deleteAttribute(index) {
      for (let i = index; i < this.attributes.length; i++) {
        delete this.selected[this.attributes[i].name];
        this.$refs[this.attributes[i].name].selectedItem = false;
      }

您能告诉我如何访问子状态吗? 例如,我想在特定子项中将某些“selectedItem”设置为 false

提前谢谢了

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    你可以使用 Alpine.$data(element) api

    <head>
      <script src="https://unpkg.com/alpinejs" defer></script>
      <script>
        let data = {
          attrs: [{
              key: 'no1',
              name: 'first'
            },
            {
              key: 'no2',
              name: 'second'
            },
            {
              key: 'no3',
              name: 'third'
            }
          ],
          toggle(index) {
            let el = document.getElementById(`child-${index}`)
            let data = Alpine.$data(el)
            data.selected = !data.selected
          }
        }
      </script>
    </head>
    
    <body x-data="data">
      <template x-for="(attr, index) of attrs">
        <div x-data="{selected: false}">
          <p :id='`child-${index}`' x-text="attr.name + (selected ? '[x]' : '[-]')"></p><button @click="toggle(index)">Toggle </button>
        </div>
      </template>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 2017-10-16
      • 2021-03-25
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多