我可能从一开始就采取了完全错误的方式,所以欢迎所有建议。
我正在尝试创建一个基本页面,右侧有输入,左侧有输入提示,当您关注输入时,相应的提示会在左侧突出显示。
这里有一个 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/