vue.jsvue-componentcode-reusevue-props

How to make text interpolation work inside css functions and router links


I was trying to implement a reusable card component, so I printed them out inside variable properties that is changed image by image

This is my code. As for title, it works perfectly. I implemented it many times, so my issue is different. I also added this props' text inside mustaches, so I can change link and image out of my card, but it doesn't work, so I need your help. I might just not understand how text interpolation works. But I think that vue supports the way to create reusable cards within a component

<template>
      <RouterLink class="card" to="{{ link }}">
      <div class="card__background" style="background-image: url({{ image }})"></div>
      <div class="card__content">
        <h3 class="card__heading">{{ title }}</h3>
      </div>
      </RouterLink>
      

</template>
<script>
import { RouterLink } from 'vue-router';
export default {
    props: ['link', 'image', 'title'],
    created() {
      console.log(this.link)
      console.log(this.image)
      console.log(this.title)
    },
    
    
}

</script>

Solution

  • I think you need to use the v-bind directive. This directive allows you to bind the value of an HTML attribute to a dynamic expression.

    Here's how you can modify your code to use the v-bind directive:

      <template>
         <RouterLink class="card" v-bind:to="link">
         <div class="card__background" v-bind:style="{ backgroundImage: `url(${image})` 
         }"></div>
        <div class="card__content">
          <h3 class="card__heading">{{ title }}</h3>
        </div>
       </RouterLink>
    
     </template>
    
     <script>
        import { RouterLink } from 'vue-router';
        export default {
        props: ['link', 'image', 'title'],
        created() {
        console.log(this.link)
        console.log(this.image)
        console.log(this.title)
        }
        }
     </script>