0

I have a set of computed data that each one of them returns a url -

computed:{
facebookUrl(){return "facebook.com"},
twitterUrl(){return "twitter.com"}
}

in the template I have a v-for loop and in each one of the items I have a 'name' (name:"facebook",name:"twitter")

now I wand to bind the computed url for each of them like this (I tried several ways, all end the same) -

:href="`${item.name}Url`"

but instead of getting the computed value I get only the strings...

and yes, I know I can use a method with param to return the value...

1
  • the value in :href will be something like 'facebookUrl', as a string. You can't create a dynamic function like this. Create a function (not computed value) that get's name as param, and returns the correct url. (use a if else, or switch case). Commented Nov 26, 2018 at 11:07

2 Answers 2

1

You can make one computed that returns a dictionary of urls instead of multiple computeds. Then you can lookup each item's url.

new Vue({
  el: '#app',
  data: {
    items: [{
        name: 'facebook'
      },
      {
        name: 'twitter'
      }
    ]
  },
  computed: {
    urls() {
      return {
        facebookUrl: 'facebook.com',
        twitterUrl: 'twitter.com'
      };
    }
  }
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <div v-for="item in items">
    {{urls[`${item.name}Url`]}}
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot access a computed property with a dynamic string. If you do not want to use a lookup method, you have 2 options.

Add the url to the item.

:href="item.url"

Return a map from your computed, props, data, etc.

:href="urls[item.name]}"

urls(){return {facebook:facebook.com, twitter:’twitter.com’} }

3 Comments

the json is more complex then what I wrote, the computed contains params...
I made it with a method for now, just wanted to be sure that there isn't a shorter way. tnx.
Shortest way is to have a map. That approach is the easiest to maintain and extend also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.