skip to Main Content

Some basic information about what I’m working on. For sake of me trying to figure this out and not disclosing all information, I will input necessary info to understand the problem. This is using VUE JS.

I’m trying to update a button’s text with a method called text –> {{ text }} //

Here’s what I’m working with:

 someName: [
    {
      someKey: "someValue"
    },
    {
      someKey: "notSomeValue"
    },

My text method is inside of the computed properties section and is written as so:

  text() {
    return this.someName.filter(u => {
      return u.someKey === "someValue" ? "turn off" : "turn on";
  })

It is not posting the strings and is instead showing the objects as the button text. What am I not understanding?

I have also tried storing the string value inside a data property and displaying that. Also did not work. I’d expect the text to be one of the two string values inside of the conditional statement.

3

Answers


  1. You can modify your text methods like this,you return a array which should return a string

    text() {
      const filteredArray = this.someName.filter(u => {
        return u.someKey === "someValue";
      });
      return filteredArray.length > 0 ? "turn off" : "turn on";
    }
    
    Login or Signup to reply.
  2. You can use Array.find for a one line solution.

    text() {
      return this.someName.find(u => u.someKey === 'someValue') ? 'turn off' : 'turn on';`
    }
    
    Login or Signup to reply.
  3. You can simply achieve this with the help of Array.some() method as It will return true if any of the objects of someName array contains someValue and then based on that we can return the button text.

    Live Demo :

    new Vue({
      el: '#app',
      data: {
        someName: [
          {
            someKey: "someValue"
          },
          {
            someKey: "notSomeValue"
          }
        ]
      },
      computed: {
        text() {
          return this.someName.some(obj => obj.someKey === 'someValue') ? "turn off" : "turn on"
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <button>{{ text }}</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search