kvdmolen
kvdmolen

Reputation: 183

Replacement for $eval in VueJS 2

$eval has been removed from Vue 2.

But, consider this JSFiddle (Vue 1): https://jsfiddle.net/kvdmolen/0w193c75

Here is JSFiddle with Vue 2.0.7: https://jsfiddle.net/kvdmolen/0w193c75/1/

Imagine this is actually a component (a table with configurable columns).

Any ideas how I should replace $eval for Vue 2?

Using eval() this doesn't work as it is outside of the v-for scope

Upvotes: 1

Views: 5324

Answers (1)

Saurabh
Saurabh

Reputation: 73649

Instead of using eval, You can write the code by calling a function from HTML, and in the field you can write a function, which will determine what will be the output.

in Html:

        <tr v-for="(item, index) in myitems">
            <td v-for="column in mycolumns" v-text="myFunc(index, column.field)"> 
            </td>
        </tr>

in Vue Component:

    mycolumns: [
            {
                column: "Todo Name",
            field: (item) =>  item.name
        },
            {
                column: "Status",
            field: (item) =>  item.status
        },
            {
                column: "Status Explanation",
            field: (item) =>  item.status == 1 ? 'Done' : 'Todo'
        }
    ]
},
methods:{
   myFunc(index, fn){
     return fn(this.myitems[index])
   }
}

check working fiddle.

However this does not seem to be very good practice, as now your data is tightly bind to your html. So your container component and presentation container are not independent, can not grow independently and are error prone as well.

Upvotes: 1

Related Questions