1

Is there a way to access other properties of the same element by another property in Vue.js ?

example:

instead of writing:

<kpi title="some_kpi" v-if="displayed_kpi==='some_kpi'"></kpi>

do something like this:

<kpi title="some_kpi" v-if="displayed_kpi===title"></kpi>

which means that I want to access the value of the title inside the v-if of the same tag. (Obviously this doesn't work like this) Is there a way ?

asma
  • 599
  • 1
  • 7
  • 19
  • `title` is a variable that will be inside `data`'s component? – Bruno Francisco Mar 15 '22 at 14:48
  • @null yes, title is available inside kpi component as props – asma Mar 15 '22 at 14:57
  • You already know the value of `title` at the same level as the `v-if`, regardless of whether `title` is dynamic or not. Just use the same value in both `title` and `v-if`. – tao Mar 15 '22 at 15:35
  • That's obviously how it is done. As I said I was wondering if there was a cooler way to do it in vue.js, looks like there isn't, so conventional solution it is. – asma Mar 25 '22 at 09:25

1 Answers1

0

Update:

You can access the attributes of an element by the $refs variable. This is a great way to get information from nested components, since you have access to the children attribute of the element. (see here)

However, adding the ref attribute will not work for your example with the v-if because when v-if is false it removes the entire element.

Plus, there would be issues of synchronization with the $refs variable and the creation of the element. Here is more on lifecycle hooks).

<button @click="$event => $forceUpdate()">update me</button>
<kpi ref="MyKpi" title="some_kpi">{{ $refs.MyKpi?.title }}</kpi>

This show how on render $refs.MyKpi does not exist because the element has not been rendered. but when you force the DOM to update. you can see that we do have access to the attributes in the kpi element.

The $refs variable gives you flexibility for more complex operations on attributes of elements.

Mike D.
  • 73
  • 6
  • 1
    This doesn't exactly answer my question but it is a workaround. In my case its not that important, I was mostly wondering if the feature existed in vue. Thank you though – asma Mar 16 '22 at 07:42
  • Have you heard of [props](https://vuejs.org/v2/guide/components-props.html) and and the [$emit](https://vuejs.org/guide/components/events.html) features. Those might be what you are looking for. – Mike D. Mar 17 '22 at 22:27
  • 1
    yes i'm familiar with props and emit, but no these are not what i'm looking for – asma Mar 25 '22 at 09:27
  • I update my answer. the $refs feature is pretty cool. – Mike D. Apr 11 '23 at 17:40