【问题标题】:Fetch the value of element dynamically in Vuejs在Vuejs中动态获取元素的值
【发布时间】:2018-08-19 18:12:20
【问题描述】:

我不确定这个问题是否与 Vue 或 JavaScript 直接相关,但由于它涉及来自 VueJs 的“引用”,所以我在这里发布了问题。

我的 DOM 中有多个输入文本元素。它们被命名为 txtScore1、txtScore2、txtScore3 等。在我的点击按钮事件中,我想从 txtScore1 中获取值。但是我怎样才能在 this.$refs.{{ #some way of references txtScore1 dynamic# }}.value 中动态传递这个引用?

我正在按如下方式创建输入元素: <input v-bind:ref="'txtScore' + props.item.Id" type="text"/>

你能帮忙吗?

谢谢, 米希尔

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

如果你说的是props数据,那么下面的做法是错误的:

<input v-bind:ref="'txtScore' + props.item.Id" type="text"/>

你应该只使用item.Id

关于你的问题,

您需要在输入处理程序中传递项目对象:

<input v-bind:ref="'txtScore' + item.Id" type="text" @input="handler(item)" />

在你的方法中:

methods: { // or, whatever you need
  handler(item) {
    //use ref value like this:
    //this.$refs['txtScore' + item.id].value
  }
}

但是,这真的没有必要,你可以简单地使用 $event 对象而不是使用 $refs:

<input type="text" @input="handler($event)" />

然后,只需使用以下内容:

handler(event) {
   console.log(event.target.value);
}

更重要的是,你为什么不直接使用v-model

<input type="text" v-model="item" />

【讨论】:

    【解决方案2】:

    您可以使用字符串连接和object property accessors/bracket notation,如下所示:

    new Vue({
      el: '#app',
      data: {
        props: {item: {Id: 11, value: "Click me"}}
      },
      mounted: function() {
        var someVar = 11;
        console.log("11:", this.$refs['txtScore' + someVar].value);
      },
      methods: {
        goClick(Id) {
          console.log('You have clicked '+ Id + ', with value: "' + this.$refs['txtScore' + Id].value + '"');
        }
      }
    })
    <script src="https://unpkg.com/vue@2.5.14/dist/vue.min.js"></script>
    <div id="app">
      <input v-bind:ref="'txtScore' + props.item.Id" type="text" v-model="props.item.value" @click="goClick(props.item.Id)" />
    </div>

    虽然你可能不需要它:

    new Vue({
      el: '#app',
      data: {
        props: {item: {Id: 11, value: "Click me"}}
      },
      methods: {
        goClick(item, value) {
          console.log('Clicked item '+ item.Id + ', with value: "' + value + '"');
        }
      }
    })
    <script src="https://unpkg.com/vue@2.5.14/dist/vue.min.js"></script>
    
    <div id="app">
      <input type="text" v-model="props.item.value" @click="goClick(props.item, $event.target.value)" />
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多