Home » vue » How to extract common HTML into a Component in Vue App?

How to extract common HTML into a Component in Vue App?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have Vue app with several components. This code is duplicated in every component at the top of its template:

<section v-if="status || warn" class="messages">
  <div class="status">{{status}}</div>
  <div class="warn">{{warn}}</div>
</section>

and this code in script part of single file component:

data() {
  return {
    status: '',
    warn: ''
  }
}

I want to extract this common code into Component named Status.vue and other components import it html part will look like:

<Status></Status>

But I do not know how to handle the data variables: status and warn? status and warn will be set to some strings depending on what response comes from API call to remote service.

Will I need to redeclare these in components where Status component is imported?

Answers:

components/status.vue

<template>
  <section v-if="status || warn" class="messages">
    <div class="status">{{status}}</div>
    <div class="warn">{{warn}}</div>
  </section>
</template>

<script>
export default {
  name: 'status',
  props: {
    warn: String,
    status: String
  }
}
</script>

in app.vue

<template>
  <div class="home">
    <!-- same as v-bind:warn and v-bind:status -->
    <!-- the value "warn" and "status" are from data(),
    and its reactive to the components, so every time warn or status changed,
    value in the <status> component will also change. -->
    <status :warn="warn" :status="status" />
  </div>
</template>

<script>
// @ is an alias to /src
import Status from '@/components/Status'
import axios from 'axios'

export default {
  components: {
    Status
  },
  data () {
    return {
      warn: '',
      status: '',
    }
  },

  actions: {
    fetchData () {
      axios.get('http://example.com/api/getItem')
        .then((response) => {
          this.warn = response.warn
          this.status = response.status
        })
    }
  }
}
</script>

status & warn in Status component will change everytime fetchData() completed successfully.

###

Yes you will still have to have these variables in the data of the component that is using the Status component. You will have to bind them to the Status props like this

<Status
  :status="status"
  :warn="warn"
>
</Status>