javascript - 如何循环访问 VueJS 中的组件列表

标签 javascript vue.js vuejs2 vue-component

我可能从一开始就采取了完全错误的方式,所以欢迎所有建议。

我正在尝试创建一个基本页面,右侧有输入,左侧有输入提示,当您关注输入时,相应的提示会在左侧突出显示。

这里有一个 JSFiddle:https://jsfiddle.net/eywraw8t/210693/

这不起作用,因为我不知道如何找到适当的提示来突出显示(并将所有其他提示的 isHighlighted 设置为 false)。

我通过在字段对象上添加突出显示的 Prop 而不是使用提示组件来设法获得一个工作示例。然而实际上,字段数据将来自数据库,因此它不会有突出显示的参数,因此提示组件似乎更明智。

简单来说我的问题是:当专注于输入时如何找到相关的提示组件?

JS Fiddle 显示没有组件的功能:https://jsfiddle.net/as2vxy79/

尝试使用组件时损坏的 JS Fiddle:https://jsfiddle.net/eywraw8t/210693/

这是 JS Fiddle 之外的 JS:

Vue.component('hint', {
    template: `
    <div class="hint" :class="{'highlight-hint': isHighlighted }">
      <slot></slot>
    </div>
  `,
  data() {
    return {
        isHighlighted: false
    }
  }
});

new Vue({
  el: "#app",
  data: {
    fields: [
      {
        'id': 'name',
        'hint': 'Put the name here'
      },
      {
        'id': 'description',
        'hint': 'Put the description here'
      },
      {
        'id': 'more',
        'hint': 'Put more here'
      }
    ]
  },
  methods: {
    onFocus(focusedField) {
        // Somehow loop through the hints
      // I am aware there is no "hints" property this is an example
      this.hints.forEach(function(field) {
        field.isHighlighted = (focusedField == field.id)
      })
    }
  }
})

最佳答案

简短回答:您不需要直接引用显示提示的组件,因为您可以使用 react 性解决此问题。

您唯一需要做的就是添加一个数据字段,用于存储要突出显示的字段 id,然后根据所选 id 有条件地将类添加到要突出显示的提示(或有条件地渲染组件)。

new Vue({
  el: "#app",
  data: {
    highlightedFieldId: '',
    fields: [
      {
        'id': 'name',
        'hint': 'Put the name here'      },
      {
        'id': 'description',
        'hint': 'Put the description here'      },
      {
        'id': 'more',
        'hint': 'Put more here'      }
    ]
  },
  methods: {
    onFocus(focusedFieldId) {
      this.highlightedFieldId = focusedFieldId;
    }
  }
})

Here's an update到你的 fiddle 。


注释:

  • 如果您确实需要直接引用,可以使用 ref directive (这也适用于 v-for 生成的组件列表)。
  • 您可能应该考虑使用工具提示作为提示。例如。使用 Element UI 的 Tooltip .

更新:

所以,here's a solution使用 ref 指令获取对突出显示的 hint 组件的引用。您可以看到我在 :ref 中使用了字段 id,但您仍然从 this.$refs[focusedFieldId] 获得一个数组,因为周围有一个 v-对于。除此之外,它非常简单。

我还更新了 hint 组件以接受 is-highlighted 属性,以便它可以自行更改其类(您之前为此使用了一个数据属性,它不会不会导致组件更新)。

关于javascript - 如何循环访问 VueJS 中的组件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51542272/

相关文章:

javascript - Google 登录 API 挂起并出现 Uncaught Error 无法从 URL 哈希获取父源

vue.js - 如何在vue-cli生成的vue.config.js中设置mini-css-extract-plugin的配置

javascript - 如何更新 Vue.JS 中的插槽

javascript - 从指令改变 prop 的正确方法是什么?

javascript - 在 SlickGrid 中设置默认排序列

javascript - PHP/Javascript 项目不断调用 your-meme-site.com

javascript - Jquery 选择器选择一个 div 下的 h4 标签

android - ListView 未在 ScrollView 和 StackLayout 内呈现,在 ios 中水平方向 - nativescript-vue

laravel - dd() 在 vue-laravel 项目 axios 调用中不起作用。是否可以在 axios 调用中使用转储?

javascript - Vue 组件 : Dropdown menu open inside div