How to use includes() or indexOf() in vuetify?

107 Views Asked by At

I am having problem with this piece of code in vuetify:

<template>
   ..... {{ countf(options[1], options[2], options[3], options[4], options[5]) }} ......
</template>


<script lang="ts">
export default Vue.extend({

data () {
  return {
    count: 1,
    str: ''
  }
},
   methods: {
      countf(a: any, b: any, c: any, d: any, e: any) {

      this.str = a.title;

        if (this.str.indexOf("Lapel") > -1) {
          this.count++;
        }
        return "Count = " + this.count;
      }
   }
 })
</script>

I want to show Count = 2 in the webpage but whenever I navigate to this page, the page hangs. Can anyone help.

1

There are 1 best solutions below

0
On

To further elabourate on my comment: the reason why your browser freezes is because the way your app is structured causes it to enter infinite recursion once any rendering is attempted:

  1. When rendering the DOM, the component's countf() method is invoked
  2. The method increments this.count and also returns a string that is not the same as before
  3. This causes the DOM to change, triggering re-rendering, thereby going back to step 1, until the browser runs out of memory

If your logic is only supposed to run once, you can either invoke it in the created or mounted lifecycle hook, and store the output in a string that is printed in the DOM. In that sense, you are ensuring that there is a one-way data flow.

An example below illustrates a possible fix. It is not sure where options is coming from, so you might need to make some adjustments:

<template>
  ..... {{ countOutput }} ......
</template>

<script lang="ts">
export default Vue.extend({
  data () {
    return {
      count: 1,
      countOutput: '',
      str: ''
    }
  },
  mounted(): {
    this.countOutput = this.countf(this.options[1], this.options[2], this.options[3], this.options[4], this.options[5]);
  },
  methods: {
    countf(a: any, b: any, c: any, d: any, e: any) {

      this.str = a.title;

     if (this.str.indexOf("Lapel") > -1) {
       this.count++;
     }

     return "Count = " + this.count;
    }
  }
})
</script>