Mark
Mark

Reputation: 852

Embedding javascript into html in Vue

So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

{{blogs[0].content}}

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

{{blogs[0].content[:100]}}

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

<b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{blogs[0].content[:10]}}
        </b-card-text>
</b-card>

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

Upvotes: 0

Views: 638

Answers (3)

Reuel Ribeiro
Reuel Ribeiro

Reputation: 1479

I'd recommend creating a filter.

Vue.filter('ellipse', function (value, size) {
  if (!value) return ''
  if (value.length < size) return value;

  return `${value.substr(0, size)}...`;
})

Then you can easily reuse throughout your code:

{{ message | ellipse(50) }}
<p v-text="message | ellipse(50)"></p>

Upvotes: 1

Jos&#233; Silva
Jos&#233; Silva

Reputation: 401

<b-card
        :title=blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{blogs[0].content[:10]}}
        </b-card-text>
</b-card>

This should work. Use v-bind to use JS in HTML tags.

See more in the docs: https://v2.vuejs.org/v2/guide/class-and-style.html

Upvotes: 1

Mitro
Mitro

Reputation: 278

you can add a method that will get a portion of blog content.

methods: {
       getContentPortion (content, maxSize) {
          if(maxSize >= content.length) {
             return content;
           }

       return `${content.substr(0, maxSize)}...`;
    }
  },

And then you can update your template with:

<b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{ getContentPortion(blogs[0].content, 10) }}
        </b-card-text>
</b-card>

Upvotes: 3

Related Questions