javascript - Format a laravel route string to be used in Vue.js component

I am passing data from a blade file to a Vue component. I am passing a collection of programs to Vue and in the collection of programs is an array and within the array are attributes. One of the attributes is a route attribute. Since the route is coming from Laravel and not vue router, (I am not using vue-router) the route has the blade file extension appended to it as it would be used in a controller when returning a view: so the way the routes are being returned right now in my Vue Component resembles:

route: program1.index,
       program2.index
       program3.index

In my index.blade.php file I bind the programs and pass it to vue:

<programs :programs="{{App\Programs::all()}}">
 </programs>

In Programs.vue I loop through the programs with v-for and am properly accessing the route like so:

   <template>
        <div>
          <a :href="program.route"></a>
        </div>
    </template>

I am using this computed property which properly strips off the .index from the routes, but when I check the value of formattedRoutes in the vue console it is undefined.

computed: {
     formattedRoutes() {
      this.programs.filter(obj => {
        return obj.route.replace(/\.[^/.]+$/, "");
      });
    }
}

This is me calling the computed property in the html:

 <template>
    <div>
       <a :href="program.formattedRoutes"></a>
    </div>
 </template>

The program.formattedRoutes returns undefined I can't figure out why.

Answer

Solution:

Two problems here...

  1. Your computed property doesn't return anything
  2. Computed properties should be pure functions. They should not manipulate any data, otherwise you can end up in an infinite loop since computed property functions execute when data changes

I would instead create a computed property to return programs with your transformed routes. For example

computed: {
  linkedPrograms: vm => vm.programs.map(program => ({
    ...program,
    route: program.route.replace(/\.\w+$/, "")
  }))
}

Now iterate linkedPrograms instead of programs and use the transformed route property in your links. For example (and this is purely guess work because you didn't show how you were iterating programs in your template)...

<!-- I'm just guessing with the "id" and "name" properties -->
<div v-for="program in linkedPrograms" :key="program.id">
  <a :href="program.route">{{ program.name }}</a>
</div>

Source