How to extract common HTML into a Component in Vue App?
How to extract common HTML into a Component in Vue App?
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?
2 Answers
2
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.
glad I can help :D
– Christhofer Natalius
Aug 26 at 18:53
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
data
Status
Status
<Status
:status="status"
:warn="warn"
>
</Status>
Baboo it seemed to be good answer but when I tried it, it does not work. The variables are not bound to Status component which get the values whatever they are assigned to in within Status component. Later changes in those variables in component where Status is imported has no effect.
– ace
Aug 26 at 17:03
If you want to react to props changes, you have to watch them. Here is the documentation.
– Baboo_
Aug 26 at 17:19
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Christ thank u for details works like a charm!
– ace
Aug 26 at 18:45