redronin
redronin

Reputation: 723

How to render filter of a nested element in Vue 2?

I had the following in Vue 1.x

<tr v-for="product in products">
   <td><img src="{{ product.image_url | thumbnail }}" class="thumbnail"></td>
</tr>

But in Vue 2 I tried:

 <tr v-for="product in products">
   <td><img :src="product.image_url | thumbnail" class="thumbnail"></td>
 </tr>

and got "Property or method "thumbnail" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option"

note: The regular mustache interpolation filter doesn't work when I'm assigning it to a property on a html element (ie: {{ data | filter }} works fine as plain text but not when trying to do src="{{ data | filter }}".

I tried a computed property but it didn't work as the element I'm trying to get a computed value is each element within an array (and I'm looping through each element in the array).

All thumbnail does is do some regex and fancy text replacement. Not sure the best way to do this in vue2.

Upvotes: 1

Views: 3066

Answers (2)

Med
Med

Reputation: 2802

Vue.js 2.0

Filters can now only be used inside text interpolations ({{}} tags). In the past we've found using filters with directives such as v-model, v-on etc. led to more complexity than convenience, and for list filtering on v-for it is more appropriate to move that logic into JavaScript as computed properties.

Using computed property:

new Vue({
    el: '#app',
    data: {
        products: [],
    },

    computed: {
        filterProducts() {
            return this.products.filter(function(product) {
                ...
            })
        }
    }
})

Upvotes: 2

Mani Jagadeesan
Mani Jagadeesan

Reputation: 24275

Vue.js expects you to define your filters before you use them in templates. Here is an example of how you would define a date formatting filter:

// Define the date time format filter
Vue.filter("formatDate", function(date) {
    return moment(date).format("MMMM D, YYYY")
})

Once you have that, you are allowed to use it in code as follows:

<div class="due-date">{{dueDate | formatDate}}</div>

Can you tell me what the thumbnail filter is supposed to do? For images, I don't think there is any processing you can do on the client side. You can show thumbnails in some pre-defined size, which is something you would do in CSS, not using filters.

Upvotes: 0

Related Questions