How do I import Axios into main.js in Vue? - javascript

I seem to not be able to use axios in my vue project as it's saying that 'axios' is not defined when I try using axios.get() in my file for Home.vue. Am I doing something wrong in main.js where I configure it? Or am I missing something that needs to be added? Below is my code for main.js and it shows how I'm adding axios to my project.
import Vue from 'vue';
import GSignInButton from 'vue-google-signin-button';
import ElementUI from 'element-ui';
import axios from 'axios';
import './assets/element-variables.scss';
import locale from 'element-ui/lib/locale/lang/en';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
Vue.use(ElementUI, { locale });
Vue.use(GSignInButton);
Vue.use(axios);
Vue.use(ElementUI);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
Edit: The solution for this issue for me was to install a vue plugin called vue-axios and follow the steps to configure here: https://www.npmjs.com/package/vue-axios

Try to add axios as instance global property instead of Vue.use(axios);:
Vue.prototype.$axios=axios
then you could use it in any child component like this.$axios.get()
learn more about adding-instance-properties

Related

How to get Vue in vue3 which is undefined in other files

Hi i have a situation something like this
I have 2 files
main.js
utils.js
main.js
import { createApp } from 'vue'
import Utils from "./utils.js"
import router from "...."
import VueCookies from 'vue-cookies'
const app = createApp(App);
app.use(router);
app.use(VueCookies)
app.use(Toast,Utils.toastConfig())
app.mount('#app')
utils.js
import Vue from 'vue'
export default{
setCookie(params){
Vue.$cookies.set(params.name, params.value)
}
...
// so on related to Vue.$cookies
}
Note: above file usage is in multiple places, changing everywhere is not feasible now as we are migrated from vue2 to vue3
Question: Vue is undefined in utils.js how to make it work without much code changes

After I have installed axios How to import it on y project vuejs

hope you are well!
I am working in a project CRUD web application that handles user management. Create user, edit user, delete user.
First I set up my project install VueJS after that installed vue-bootstrap make import in file main.js.
For mocking the Backend I have used :
NPM install -g json-server
After that, create a new file called db.json that handles users in the root of a project.
I run command json-server --watch db.json to make record available.
http://localhost:3000/users
I have installed axis for us to be able to send and receive data from our backand.
So I have run command npm install axios.
But after it how I have import axios in file main.js, but I am not confident if is the right way?? Thanks
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { BootstrapVue, IconsPlugin } from "bootstrap-vue";
import axios from 'axios'
//Import Bootstrap an BootstrapVue CSS files (order is important)
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
Vue.config.productionTip = false
Vue.use({
install (Vue) {
Vue.prototype.$api = axios.create({
baseURL: 'http://localhost:8000/users/'
})
}
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
<script>
import axios from 'axios';
export default {
data() {
return {
posts: [],
errors: []
}
},
// Fetches posts when the component is created.
created() {
axios.get(`http://jsonplaceholder.typicode.com/posts`)
.then(response => {
// JSON responses are automatically parsed.
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
Do the same as shown in the script example, it will work
Fetching data from external sources is considered as a "side-effect". Thus, according to me, you should perform such side effects inside a "mounted" life cycle.
Further, to make things more better, you can create an abstraction layer for fetching data from external APIs inside "mounted" life cycle.
To make things simple on your end, you can also consider Vue-Query.
the easiest way is to create a folder known as axios in your src then add index.js in it then put this code:
// axios/index.js
import axios from "axios";
export default axios.create({
baseURL: "http://127.0.0.1:8000/api/", //your base url here
});
then import this file as axios in your app main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { BootstrapVue, IconsPlugin } from "bootstrap-vue";
import axios from "#/axios"; //import your custom axios

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=31b05063' does not provide an export named 'default'

I don't know how to solve this problem.
When I started project vue3.js , console show me this error.
This import in pinia store.
I tryied change first line with import to
"import Vue from 'vue';" (without curcy braces), but error don't disappear.
import { Vue } from 'vue';
import { defineStore } from 'pinia';
import moment from 'moment';
import _ from 'lodash';
import router from '#/router';
if you are using latest version of vue , vue3
this code
import { Vue } from 'vue';
is no longer global instance

Vue JS NPM Module imported into Component

I am trying to import an npm package into my vue.js component. Specifically, I am trying to import ScrollMagic into my project, but I am getting it to be undefined.
I have seen people suggest previously that it should be in my mounted() hook, which I am doing but my import statements (I have tried both in main.js, and in the components tag but both have returned undefined variables. Any direction would be appreciated.
Script for my component:
<script>
import { ScrollMagic } from 'scrollmagic';
export default {
name: 'Scroller',
mounted() {
console.log(ScrollMagic);
},
};
</script>
And in my main.js
import Vue from 'vue';
/*
IMPORT STATEMENTS FOR MODULES GO HERE
*/
import sm from 'scrollmagic';
import gsap from 'gsap';
import App from './App.vue';
import './registerServiceWorker';
import router from './router';
Vue.config.productionTip = false;
/*
Usage statement
*/
Vue.use(sm);
Vue.use(gsap);
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');
Maybe the scrollmagic package doesn't export a variable or function ScrollMagic, so it keeps getting undefined?
Have you tried:
import * as ScrollMagic from 'scrollmagic';
// OR
import ScrollMagic from 'scrollmagic';

axios is not defined in vue js cli

I installed axios using the npm install axios command this is my package.json dependencies
"dependencies": {
"axios": "^0.18.0",
"bootstrap-vue": "^2.0.0-rc.11",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
I registered the axios in my main.js file.
import Vue from 'vue'
import VueRouter from 'vue-router'
import BootstrapVue from 'bootstrap-vue'
import axios from 'axios'
import App from './App'
import routerList from './routes'
Vue.use(axios)
Vue.use(BootstrapVue)
Vue.use(VueRouter)
When I tried to use axios in one of my components I get this error:
Uncaught ReferenceError: axios is not defined
How to fix this?
Vue.use means adding plugins. However, axios is not a plugin for Vue, so you can not add it globally via use.
My recommendation is importing axios only when you need it. But if you really need to access it globally, you may like to add it to prototype.
Vue.prototype.$axios = axios
Then you can access axios in vue using this.$axios
Solution 1 (Not recommended):
In main.js, add this line instead of import axios from 'axios'
window.axios = require('axios');
And remove
Vue.use(axios)
Solution 2 (Recommended Approach):
Using window is generally considered a bad practice, so you better use axios the following way:
Create a folder named plugins inside of your src directory.
Then, create axios.js file inside that directory. We will put all our axios logic here and use axios as a Vue plugin.
Add the following:
import ax from 'axios'
// insert all your axios logic here
export const axios = ax
export default {
install (Vue, options) {
Vue.prototype.$axios = ax
}
}
In src/main.js, add the following:
import Vue from 'vue' // You can skip this line
import VueAxios from './plugins/axios'
Vue.use(VueAxios)
Now, you can use axios as this.$axios in your components. So something like this.$axios.get().
Therefore, you can import axios with the following line:
import { axios } from '#/plugins/axios'
Now, you can use axios directly in your store.
Or you can also use it as Vuex plugin:
import { axios } from '#/plugins/axios'
const axiosPlugin = store => {
store.$axios = axios
}
new Vuex.Store({
...,
plugins: [axiosPlugin]
})
Now, you can use it as this.$axios in Vuex.
Use following command to install axios
npm install axios --save
After executing above command import like mentioned below:
import axios from 'axios'
Also install vue-axios and import in main.js
import VueAxios from 'vue-axios'
Then in main.js:
Vue.use(VueAxios, axios)
Now if I am not mistaken in your methods you can use for example:
let uri = 'http://localhost:4000/tickets/add';
this.axios.post(uri, this.ticket).then((response) => {
console.log(response);
});
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios;
then inside your component you can start using axios like this:
{
methods: {
someMethod() {
this.$http.get('/users').then(() => {
// do something
})
}
}
}
Include this line:
import {AxiosInstance as axios} from "axios";
To use in Vue Components, install both Vue Axios and Axios packages
npm install --save axios vue-axios
In your main.js file, add the following:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
With the above solution, I never had an issue using axios in my Vue components with this keyword till now.
Custom Javascript File
However, I had faced issues using Axios in a custom JS file with axios not defined error.
Following worked for me in a custom JS file:
const axios = require("axios");
Usage example:
export default {
fetchProducts() {
return axios.get(`${ROOT_URL}/products`);
},
};
Try this codes:
import axios from 'axios'
Vue.use(axios)

Categories

Resources