Vue composition API use VueAxios? - javascript

I am in main.js importing vue-axios
main.js
import { createApp } from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import App from './App.vue';
const app = createApp(App);
app.use(VueAxios, axios);
app.mount('#app');
and App.vue
export default {
name: 'App',
setup() {
axios.get('xxxx').then((res) => {console.log(res)}); // is not working
}
};
but it seems Vue composition API setup can't get axios? So it must be used in App.vue import axios from 'axios'?
import axios from 'axios';
export default {
name: 'App',
setup() {
axios.get('xxxx').then((res) => {console.log(res)});
}
};
My environment is vite

generally I'd do something like this ( except I modularize all the api calling into a "service" rather than inlining it into the view code.)
import axios from 'axios';
import {onMounted} from 'vue'
export default {
name: 'App',
setup() {
onMounted(async () => {
let res = await axios.get('xxxx')
console.log(res)
});
}
};

This wouldn't work in any version of Vue without an import:
axios.get(...)
Even in Vue 2, you have to use one of these if you use vue-axios:
this.axios.get(...)
this.$http.get(...)
Vue.axios.get(...)
The composition API has no this access in the component, so vue-axios doesn't help much.

Related

Can't use Vuex to display data

I am a new .net+vuejs learner and i'm using
this project template for vuejs
I'm trying to use vuex in my project to display countries data from database but it doesn't work
main.js
import 'bootstrap/dist/css/bootstrap.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
index.js
import { createApp } from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import countries from "./module/countries/countries";
createApp(App).use(Vuex);
export default new Vuex.Store({
modules: {
countries: countries
}
});
store file
import axios from "axios";
const state = {
countries:[]
};
const countries = {
async getCountries({ commit }, payload) {
const result = await axios.get("Pho/GetCountries");
return result.data;
}
};
export default {
namespaced: true,
state,
mutations,
countries,
getters
}
my component
<script>
import axios from 'axios'
import swal from 'sweetalert';
export default {
name: "Home",
data() {
return {
countries: [],
}
},
methods: {
getCountries: async function () {
this.countries = await this.$store.dispatch("countries/getCountries");
}
},
mounted() {
this.getCountries();
}
}
</script>
ERROR: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'dispatch')
i tried to import store to my main.js like this
import 'bootstrap/dist/css/bootstrap.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './index.js'
createApp(App).use(router, store).mount('#app')
but the app doesn't ever lauch
It is not good practice to call APIs from storage files. Use vuex storage for only storage, use mixins(recommended) or component methods for sending API. I will show a simple approach to managing vuex storage!
Storage File: index.js
import Vue from 'vue'
Vuex from 'vuex'
import router from '../router/index'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
countries:[]
},
getters: {},
mutations: {
countriesChanger(state, payload) {
state.countries = payload;
},
},
actions: {},
});
Component File: MyComponent.vue
<template>
<li v-for="country in countries">
{{country}}
</li>
</template>
<script>
export default {
name: "Home",
data() {
return {
countries: [],
}
},
mounted() {
this.getCountries(); // assume this function calls to your API
},
watch: {
"$store.state.countries": function () {
// Listens when countries in storage updated
this.countries = this.$store.state.countries;
}
}
</script>
To change vuex storage item (to update countries) , use mutations after getting data from your API:
this.$store.commit("countriesChanger", countriesFromAPI);
That's it!

How to use $axios Nuxt module inside of setup() from composition API?

The docs say to use this.$axios.$get() inside of methods/mounted/etc, but that throws TypeError: _this is undefined when called inside of setup(). Is $axios compatible with the composition API?
To clarify, I'm specifically talking about the axios nuxt plugin, not just using axios generically. https://axios.nuxtjs.org/
So for instance, something like this throws the error above
export default {
setup: () => {
const data = this.$axios.$get("/my-url");
}
}
import { useContext } from '#nuxtjs/composition-api';
setup() {
const { $axios } = useContext();
}
Alright, so with the usual configuration of a Nuxt plugin aka
plugins/vue-composition.js
import Vue from 'vue'
import VueCompositionApi from '#vue/composition-api'
Vue.use(VueCompositionApi)
nuxt.config.js
plugins: ['~/plugins/vue-composition']
You can then proceed with a test page and run this kind of code to have a successful axios get
<script>
import axios from 'axios'
import { onMounted } from '#vue/composition-api'
export default {
name: 'App',
setup() {
onMounted(async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
console.log(res)
})
},
}
</script>
I'm not sure about how to import axios globally in this case but since it's composition API, you do not use the options API keys (mounted etc...).
Thanks to this post for the insight on how to use Vue3: https://stackoverflow.com/a/65015450/8816585

Using momentJS globally in VueJS 3

In VueJS 2, I could use momentJS globally like this:
in main.js:
import moment from 'moment';
moment.locale('fr');
Object.defineProperty(Vue.prototype, '$moment', { value: moment });
in any component:
{{ item.date_creation?$moment(item.date_creation).format('l'):'No date'}}
In VueJS 3 I tried to do the following in main.js:
import { createApp } from 'vue';
import moment from 'moment';
import App from './App.vue';
import './registerServiceWorker';
import router from './router';
import store from './store';
moment.locale('fr');
createApp(App).use(moment).use(store).use(router)
.mount('#app');
But actually I can't use "moment" in any of my component, I have to import "moment" in each of them.
Isn't there a better solution? I read a lot of documentation and tutorials, I didn't see anything good...
Thanks in advance.
Edit: here is how I use $moment in my component:
<template>
<div class="xx" :key="'title-'+myReactiveVariable.title">
<h1>{{ myReactiveVariable.title }}</h1>
<div class="yy">
{{ myReactiveVariable.content }}
</div>
<footer>
Sent on
{{ myReactiveVariable.date }}
by {{ myReactiveVariable.author }}
<who-is-it :idSent="id" :key="'ID-'+id">
</who-is-it>
</footer>
</div>
</template>
<script>
// # is an alias to /src
import WhoIsIt from '#/components/WhoIsIt.vue';
import {
defineComponent, reactive, onMounted, watch, ref,
} from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
export default defineComponent({
name: 'XXX',
components: {
WhoIsIt,
},
setup() {
const route = useRoute();
const myReactiveVariable = reactive({
title: '',
content: '',
date: '',
});
const id = ref('');
async function fetchArticle(id) {
console.log(`A: ${process.env.VUE_APP_API_URL} - ${id}`);
const res = await axios.get(`${process.env.VUE_APP_API_URL}/whoarewe/${id}`);
id.value = res.data.author;
myReactiveVariable.titre = res.data.title;
myReactiveVariable.content = res.data.content;
myReactiveVariable.date = this.$moment(res.data.date).format('l');
}
watch(() => route.params.id, () => {
fetchArticle(route.params.id);
});
onMounted(async () => {
fetchArticle(route.params.id);
});
return {
myReactiveVariable,
id,
};
},
});
</script>
Add the moment to the global config properties app.config.globalProperties.$moment=moment:
import { createApp } from 'vue';
import moment from 'moment';
import App from './App.vue';
import './registerServiceWorker';
import router from './router';
import store from './store';
moment.locale('fr');
let app=createApp(App);
app.config.globalProperties.$moment=moment;
app.use(store).use(router)
.mount('#app');
then use this.$moment in any child component with option api, with composition you should use getCurrentInstance :
import { getCurrentInstance } from 'vue'
setup(){
const internalInstance = getCurrentInstance()
...
myReactiveVariable.date = internalInstance.appContext.config.globalProperties.$moment(res.data.date).format('l');
}
You couldn't do app.use(moment) since moment is not a Vue plugin.

How to initialize NCForms library in VueJs

I'm new to Vue CLI, and I'm trying to build a small application. As part of this I want to generate some forms.
I've tested a few libraries, and NCForms seems to do all I need to do. (specifically, I need to handle capturing of multiple arrays).
I tried to initialize the library as described in the documentation - but it fails in the Template saying that it can't find some of the element-ui components.
I'm pretty sure that I've followed the instructions properly - but I must be missing something small.
My main.js file looks like this:
import 'ant-design-vue/lib/style/index.less' // antd core styles
import './#kit/vendors/antd/themes/default.less' // default theme antd components
import './#kit/vendors/antd/themes/dark.less' // dark theme antd components
import './global.scss' // app & third-party component styles
import Vue from 'vue'
import VuePageTitle from 'vue-page-title'
import NProgress from 'vue-nprogress'
import VueLayers from 'vuelayers'
import BootstrapVue from 'bootstrap-vue'
import VueFormulate from '#braid/vue-formulate'
// Form generator: Vue-Form-Generator: https://github.com/vue-generators/vue-form-generator
import VueFormGenerator from 'vue-form-generator'
import 'vue-form-generator/dist/vfg.css'
// Form generator: NCForms: https://github.com/ncform/ncform
import vueNcform from '#ncform/ncform'
// eslint-disable-next-line no-unused-vars
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import ncformStdComps from '#ncform/ncform-theme-elementui'
// REST Calls: Axios: https://github.com/axios/axios
import axios from 'axios'
// Local files
import App from './App.vue'
import router from './router'
import store from './store'
import { i18n } from './localization'
import './antd'
import './registerServiceWorker'
// mocking api
import './services/axios/fakeApi'
Vue.use(BootstrapVue)
Vue.use(VueLayers)
Vue.use(NProgress)
Vue.use(VuePageTitle, {
prefix: 'Nedbank PhishTank | ',
router,
})
// Form generator: Vue-Form-Generator
Vue.use(VueFormGenerator)
// Form generator: NCForms
Vue.use(vueNcform, { extComponents: ncformStdComps, lang: 'en' })
window.$http = Vue.prototype.$http = axios
Vue.use(VueFormulate)
Vue.config.productionTip = false
const nprogress = new NProgress({ parent: 'body' })
new Vue({
router,
store,
nprogress,
i18n,
render: h => h(App),
}).$mount('#app')
My template looks like this:
<template>
<div>
<ncform :form-schema="formSchema" form-name="settings-form" v-model="item" #submit="submit()"></ncform>
<el-button #click="submit()">Submit</el-button>
</div>
</template>
<script>
export default {
data() {
return {
formSchema: {
type: 'object',
properties: {
name: {
type: 'string',
},
},
},
item: {
name: 'Peter Pan',
},
}
},
methods: {
submit () {
this.$ncformValidate('settings-form').then(data => {
if (data.result) {
console.log(this.$data.formSchema.value)
// do what you like to do
alert('finally!!!')
}
})
},
},
}
</script>
The error is:
Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
Am I missing something like registering the individual components? I thought this line would take care of it: Vue.use(vueNcform, { extComponents: ncformStdComps, lang: 'en' })
It feels like I should put something into the "new Vue()" statement - but I'm not sure what....
In main.js, you need to specify: Vue.use(Element);

[Vue warn]: Computed property "axios" is already defined in Data. at <App>

I know similar questions already present in stackoverflow, but I still can't understand how to solve this. I am having the warning(look in the title) in my console.
You can reproduce the warning by the following code
//index.js
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
import axios from 'axios';
const app = createApp(App)
app.__proto__.axios = axios
app.use(store)
app.mount("#app")
##App.vue
<template>
<div class="TodoList">
<p v-for="todo in todos" :key="todo.id">{{ todo.title }}</p>
</div>
</template>
<script>
export default {
mounted() {
this.$store.dispatch("fillItems");
},
computed: {
todos() {
return this.$store.getters.todos;
},
},
};
</script>
<style>
</style>
##store.js
import { createStore } from 'vuex';
export const store = createStore({
state: {
todos: []
},
getters: {
todos(state) {
return state.todos
}
},
mutations: {
FILL_ITEMS(state, payload) {
state.todos = payload
}
},
actions: {
fillItems({ commit }) {
this.axios
.get("https://jsonplaceholder.typicode.com/todos")
.then(res => commit('FILL_ITEMS', res.data))
}
}
})
You could add axios to app.config.globalProperties in order to access it inside any child component :
const app = createApp(App)
app.config.globalProperties.axios=axios
in child component use this.axios
but you couldn't access it inside the store context because this in the actions refers to the store instance, so you should import axios inside the store file and use it like :
import { createStore } from 'vuex';
import axios from 'axios';
export const store = createStore({
state: {
todos: []
},
getters: {
todos(state) {
return state.todos
}
},
mutations: {
FILL_ITEMS(state, payload) {
state.todos = payload
}
},
actions: {
fillItems({ commit }) {
axios
.get("https://jsonplaceholder.typicode.com/todos")
.then(res => commit('FILL_ITEMS', res.data))
}
}
})
or you could assign axios to the store instance (It's not recommended specially with typescript) :
const app = createApp(App)
store.axios = axios
app.use(store)
app.mount("#app")
In Vue 3, you can create app globals for components using provide/inject:
Providing
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
import axios from 'axios';
const app = createApp(App)
app.provide('axios', axios); // Providing to all components here
app.use(store)
app.mount("#app")
Injecting
In the options API:
export default {
inject: ['axios']; // injecting in a component that wants it
}
In the composition API:
const { inject } = Vue;
...
setup() {
const axios = inject('axios'); // injecting in a component that wants it
}
Edit:
I answered too fast (thanks #BoussadjraBrahim), you're not asking about components, but I'll leave that answer too. If you just want to use axios in a separate module, you can use it like any import:
import axios from 'axios';
and use axios instead of this.axios

Categories