// src/plugins/myPlugin.js
export default {
install(app, options) {
// Adding a global method
app.config.globalProperties.$formatDate = function (dateStr) {
const options = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(dateStr).toLocaleDateString(undefined, options);
};
}
};
import { createApp } from 'vue';
import App from './App.vue';
import myPlugin from './plugins/myPlugin';
const app = createApp(App);
// Register the plugin
app.use(myPlugin);
app.mount('#app');
<template>
<div>
<p>Original Date: {{ date }}</p>
<p>Formatted Date: {{ formattedDate }}</p>
</div>
</template>
<script>
export default {
data() {
return {
date: '2024-07-16'
};
},
computed: {
formattedDate() {
return this.$formatDate(this.date);
}
}
};
</script>
// src/plugins/httpClient.js
import axios from 'axios';
export default {
install(app, options) {
// Create an Axios instance
const axiosInstance = axios.create({
baseURL: options.baseURL,
headers: options.headers
});
// Adding a global method to make HTTP requests
app.config.globalProperties.$http = axiosInstance;
}
};
import { createApp } from 'vue';
import App from './App.vue';
import httpClient from './plugins/httpClient';
const app = createApp(App);
// Register the HTTP client plugin with options
app.use(httpClient, {
baseURL: 'https://api.example.com',
headers: {
'Authorization': 'Bearer your-token'
}
});
app.mount('#app');
<template>
<div>
<button @click="fetchData">Fetch Data</button>
<pre>{{ data }}</pre>
</div>
</template>
<script>
export default {
data() {
return {
data: null
};
},
methods: {
async fetchData() {
try {
const response = await this.$http.get('/endpoint');
this.data = response.data;
} catch (error) {
// Handle error
}
}
}
};
</script>