[Vuejs]-VueJS bind attribute to component in App.vue

2πŸ‘

βœ…

Add a prop to the Icon component, like so:

<template>
  <div class="container iconBar">
    <div class="row">
      <div class="col text-center py-5">
        <img :src="iconUrl" :alt="iconAlt">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['iconUrl', 'iconAlt']
}
</script>

take a look at the documentation: https://v2.vuejs.org/v2/guide/components-props.html

You could also add validation to it to ensure it’s supplied and is a string:

<script>
export default {
  props: {
    iconUrl: {
      type: String,
      required: true
    }
  }
}
</script>
πŸ‘€Victor P

1πŸ‘

In your Icon.vue file, add your props.


<template>
  <div class="container iconBar">
    <div class="row">
      <div class="col text-center py-5">
        <img :src="{ iconUrl }" :alt="{ iconAlt }">
      </div>
    </div>
  </div>
</template>

<script>
    export default {
        props: ['iconUrl', 'iconAlt'],
    }
</script>

πŸ‘€Alagie Sellu

1πŸ‘

Consider not using camelcase convention to call props in your component instead use kebab-case like this:

Vue.component('icon-component', {
  props: ['iconName', 'iconAlt'],
  data () {
    return {
      iconUrl: '../assets/img/' + this.iconName + '.svg'
    }
  },
  template: `
    <div class="container iconBar">
      <div class="row">
        <div class="col text-center py-5">
          <img :src="iconUrl" :alt="iconAlt">
            <p>icon url path: {{ iconUrl }}</p>
        </div>
      </div>
    </div>
  `,
})

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <icon-component
    icon-name="plant-icon-1" 
    icon-alt="Blume" 
  />
</div>

Leave a comment