Vue Js Axios get method - vue.js

I use vue.js and I try to set a parameter id in axios.get request and I can't understand how exactly to do it
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Movie from './views/Movie.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
},
{
path: '/movie/:m_id',
name: 'movie',
component: Movie
}
]
})
import Navbar from '../components/Navbar'
import axios from "axios"
export default {
components:{
Navbar
},
data () {
return {
movi: null,
}
},
mounted () {
axios
.get(`https://api.themoviedb.org/3/movie/${m_id}?api_key=7bc75e1ed95b84e912176b719cdeeff9&language=en-US`)
.then(response => (this.movi= response.data))
}
}
I am trying to pass to axios this id of the page to get information about that specific movie and I got stuck.
Any help?

You can try this to use your params from the URL:
// Retrieve the `m_id` param from the `this.$route.params` object:
this.$route.params.m_id
For more info see https://router.vuejs.org/api/#route-object-properties

#How can I do the same thing but in Vuex
import Vue from 'vue'
import Vuex from 'vuex'
import Axios from 'axios';
import router from './router'
Vue.use(Vuex)
Vue.use(Axios)
Vue.use(router)
export default new Vuex.Store({
// data() {
// return {
// m_id:this.$route.params.m_id
// }
// },
// m_id : this.$route.params.m_id,
state: {
video_key: [],
},
mutations: {
updateInfo (state , video_key){
state.video_key = video_key
}
},
getters:{
m_id : this.route.params.m_id
},
actions: {
fetchData({commit,getters}){
axios.get(`https://api.themoviedb.org/3/movie/${this.m_id}/videos?api_key=7bc75e1ed95b84e912176b719cdeeff9&language=en-US`)
.then(response =>{
commit('updateInfo',response.data.results[0].key)
})
}
}
})

Related

Accessing to store in the router

I would like to check in my Vuex store whether a user has the 'admin' role before entering the /dashboard route. But I can't properly access data from store.getters.
I use Quasar (Vue.js) and Vuex + Typescript.
In the routes.ts file, on the beforeEnter() function, I can access getters from the store with a console.log(store.myStore.getters). Here I see userInfos inside:
I don't understand why I only get {} and not {...} (Note that if I click on it, I see its contents).
But if I call console.log(store.myStore.getters.userInfos), I don't see the data:
Here is index.ts (router):
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import { Store } from 'vuex'
import { StateInterface } from '../store'
import routes from './routes'
export default route<Store<StateInterface>>(function ({ Vue }) {
Vue.use(VueRouter)
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE
})
return Router
})
Here is routes.ts (router):
import { RouteConfig } from 'vue-router'
const routes: RouteConfig[] = [
{
path: '/',
component: () => import('layouts/Login.vue'),
children: [
{ path: '', component: () => import('pages/Index.vue') },
{ path: '/inscription', component: () => import('pages/SignUp.vue') },
{ path: '/connexion', component: () => import('pages/SignInPage.vue') }
]
},
{
path: '/main',
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('pages/Index.vue') },
{ path: '/dashboard', component: () => import('pages/DashboardB2B.vue'),
beforeEnter: (to, from, next) => {
const store = require('../store')
console.log("before enter")
console.log(store.myStore.getters)
return next();
}, },
{
path: '/ajouter-un-referentiel',
component: () => import('pages/ReferentielMetier.vue')
},
{
path: '/init',
component: () => import('components/bot/BotSkeleton.vue')
}
]
},
{
path: '/bot',
component: () => import('layouts/Bot.vue'),
children: [
{
path: '/ajouter-un-referentiel',
component: () => import('pages/ReferentielMetier.vue')
},
{
path: '/init',
component: () => import('components/bot/BotSkeleton.vue')
}
]
},
// Always leave this as last one,
// but you can also remove it
{
path: '*',
component: () => import('pages/Error404.vue')
}
]
export default routes
And here is index.ts with the store (Vuex):
import Vue from 'vue'
import { store } from 'quasar/wrappers'
import Vuex from 'vuex'
Vue.use(Vuex)
import matching from './modules/matching'
import orga from './modules/organigrame'
import user from './modules/user'
export interface StateInterface {
example: unknown
}
let myStore: any
export default store(function({ Vue }) {
Vue.use(Vuex)
const Store = new Vuex.Store<StateInterface>({
modules: {
matching,
orga,
user
},
// enable strict mode (adds overhead!)
// for dev mode only
strict: !!process.env.DEBUGGING
})
myStore = Store
return Store
})
export {myStore}
EDIT: Looks like my console.log runs before the getters are loaded, because when I check out Vue developer tools, I see everything. How can I check the store if the store itself doesn't load before the beforeEnter function?
please try like this
store.myStore.getters["userInfos"]
I'm having exact issue, even if i use async/await :S
try this
router.beforeEach(async(to, from, next) => {
const userInfo = await store.getters.userInfos;
console.log(userInfo);
});

Vue - Can I change a routers component based on the value of an item in the store?

So I want to change a routers component based on a state in my store. This means that, depending on the state in the store, the router can display a different template page.
Router.js:
import Router from 'vue-router'
import store from './store'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Homepage',
component: () => import('#/' + store.state.theme.path + '/components/Hello')
},
{
path: '/admin',
name: 'Admin',
component: () => import('#/cms/components/Admin')
}
]
})
Store.js:
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
theme: {
path:'theme-00'
}
},
getters: {
theme: state => {
return state.theme.path;
}
}
});
Any help is welcome!
Thanks,
Justin.

VueJs: cannot use router.push

So, i want to vue router.push on my store.js, but i keep getting error Cannot read property 'push' of undefined
i've tried to import vue-router in my store.js, but still in vain
here's my app.js :
import Vue from 'vue'
import VueRouter from 'vue-router'
//Import and install the VueRouter plugin with Vue.use()
Vue.use(VueRouter)
import App from './views/App'
import Home from './views/Home'
import Login from './views/Login.vue'
import Register from './views/Register.vue'
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
name: 'home',
component: Home,
meta: { requiresAuth: true }
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
],
});
const app = new Vue({
el: '#app',
components: { App },
router,
});
and here's my store.js :
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
accessToken: null,
loggingIn: false,
loginError: null
},
mutations: {
loginStart: state => state.loggingIn = true,
loginStop: (state, errorMessage) => {
state.loggingIn = false;
state.loginError = errorMessage;
},
updateAccessToken: (state, accessToken) => {
state.accessToken = accessToken;
},
logout: (state) => {
state.accessToken = null;
}
},
actions: {
doLogin({ commit }, loginData) {
commit('loginStart');
console.log(loginData)
axios.post('http://localhost:8000/api/login', loginData)
.then(response => {
console.log(response)
let accessToken = response.data.jwt;
document.cookie = 'jwt_access_token=' + accessToken;
commit('updateAccessToken', accessToken);
///this caused the error
this.$router.push({ path: '/' })
})
.catch(error => {
// commit('loginStop', error.response.data.error);
console.log(error)
commit('updateAccessToken', null);
console.log(error.response);
})
}
}
})
as you can see, after i call doLogin() function, and using axios, it stop at the this.$router.push({ path: '/' }) line, causing error.
You need to make a router.js file
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
...
})
export default router
In app.js replace the import of the vue-router to your new router.js and remove Vue.use(Router).
In the store, this is not the Vue instance.
Import the router.js in your store.js;
import router from './router'
Then you can access it like this;
router.push({ path: '/' })
I also noticed that you haven't add the store to the Vue instance. Import and add in app.js.
import store from './store'
...
const app = new Vue({
el: '#app',
components: { App },
router,
store //<<<<<<<<
});

vuejs vue-router: TypeError: Cannot read property 'push' of undefined [duplicate]

This question already has answers here:
How to navigate using vue router from Vuex actions
(6 answers)
Closed 3 years ago.
I am having trouble loading a page with vue-router. It appears that my $router var isn't being reached.
When I console log this.$router I receive an undefined. However, console logging this returns the store object in dev tools.
Here are the relevant scripts:
main.js
import Vue from "vue";
import VueCookies from 'vue-cookies';
import App from "./App.vue";
import router from "./router";
import { store } from "./store/store";
import BootstrapVue from "bootstrap-vue";
import "./registerServiceWorker";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
import "../css/bracket.min.css";
Vue.use(BootstrapVue);
Vue.use(VueCookies);
// set default config
VueCookies.config('1d');
// set global cookie
VueCookies.set('theme','default');
VueCookies.set('hover-time','1s');
require("../css/bracket.min.css");
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
router.js
import Vue from "vue";
import Router from "vue-router";
// import Home from "#/views/Home.vue";
import Splash from "#/components/Splash.vue";
import Dash from "#/components/Dash.vue";
import Signup from "#/views/Signup.vue";
import finalSignup from "#/components/finalSignup.vue";
import providerDash from "#/views/ProviderDash.vue";
import employeeDash from "#/views/EmployeeDash.vue";
import Login from "#/views/Login.vue";
Vue.use(Router);
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "home",
component: Splash
},
{
path: "/login",
name: "login",
component: Login
},
{
path: "/signup",
name: "signup",
component: Signup
},
{
path: "/provider-full-name",
name: "finalSignup",
component: finalSignup
},
{
path: "/provider-dashboard",
name: "providerDash",
component: providerDash
},
{
path: "/employee-dashboard",
name: "employeeDash",
component: employeeDash
},
{
path: "/about",
name: "about",
component: () =>
import(/* webpackChunkName: "about" */ "./views/About.vue")
}
]
});
userSession.js (vuex module)
-The action in question is named authenticateUserSession
import Axios from "axios";
const userSession = {
namespaced: true,
state: {
email: '',
password: ''
},
mutations: {
SET_EMAIL: (state, payload) => {
state.email = payload;
},
SET_PASSWORD: (state, payload) => {
state.password = payload;
}
},
actions: {
setEmail(context, email) {
context.commit('SET_EMAIL', email)
},
setPassword(context, password) {
context.commit('SET_PASSWORD', password)
},
authenticateUserSession(context, {email, password}) {
context.dispatch('setEmail', email);
context.dispatch('setPassword', password);
Axios.post('http://localhost:3000/api/v1/sessions', {}, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'user-email': context.state.email,
'user-password': context.state.password
}
})
.then((response) => {
// console.log(response.data.locals.token);
// console.log(this.$router);
// console.log(this);
let jwt = response.data.locals.token
window.$cookies.set('jwt', jwt);
this.$router.push("home");
})
.catch(function(error) {
console.log(error);
})
}
},
getters: {
getEmail: (state) => {
return state.email;
},
getPassword: (state) => {
return state.password;
}
}
}
export default userSession;
Why am I missing access to the vue-router variable ($router/this.$router) & unable to render a specified route?
The content in #yuriy636's link in addition to the other links in the post helped me resolve!
I ended up doing the following:
import router from "../../router";
.
.
.
// inside the authenticateUserSession action, in axios response
router.push("home")";
Many thanks #yuriy636!

Load routes from api in vue

I'm trying to load routes in a Vue application from my API. I tried pushing data to routes variable and using addRoutes method. But no luck. I think there could be an issue with async. But why the addRoutes() not working?
Here's my code:
import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
/**
* Routes
*/
import item_index from '../../app/Tenant/Item/Views/Index.vue';
import contact_index from '../../app/Tenant/Contact/Views/Index.vue';
import eav_index from '../../app/Tenant/Eav/Views/create.vue';
import eav_create from '../../app/Tenant/Eav/Views/create.vue';
var routes = [
{ path: '/items', component: item_index, name: 'item_index' },
{ path: '/contact', component: eav_index , name: 'contact_index' , props: { entity_type_id: 1 }},
];
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
linkActiveClass: 'active',
routes
});
axios
.get('http://c1.fmt.dev/api/eav/entity_types')
.then(response => {
for (var i = 0; i < response.data.length; i++) {
var type = response.data[i];
var route = {
path: '/' + type.name,
component: eav_index,
name: type.name + '_index',
props: {
entity_type_id: type.id
},
};
router.addRoutes([route]);
alert(router.options.routes);
// alert(JSON.stringify(routes));
}
})
.catch(error => {
console.log(error)
});
new Vue({
el: '.v-app',
data(){
return {
page_header: '',
page_header_small: '',
}
},
router, axios
});
Try this improved code. Without postponing Vue instance creation, so without unnecessary delaying page interactivity:
import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import item_index from '../../app/Tenant/Item/Views/Index.vue'
import contact_index from '../../app/Tenant/Contact/Views/Index.vue'
import eav_index from '../../app/Tenant/Eav/Views/create.vue'
import eav_create from '../../app/Tenant/Eav/Views/create.vue'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
linkActiveClass: 'active',
routes: [{
path: '/items',
component: item_index,
name: 'item_index'
}, {
path: '/contact',
component: eav_index ,
name: 'contact_index' ,
props: {entity_type_id: 1}
}]
})
new Vue({
el: '.v-app',
router,
data () {
return {
page_header: '',
page_header_small: '',
}
},
methods: {
getDynamicRoutes (url) {
axios
.get(url)
.then(this.processData)
.catch(err => console.log(err))
},
processData: ({data}) => {
data.forEach(this.createAndAppendRoute)
},
createAndAppendRoute: route => {
let newRoute = {
path: `/${route.name}`,
component: eav_index,
name: `${route.name}_index`,
props: {entity_type_id: route.id}
}
this.$router.addRoutes([newRoute])
}
},
created () {
this.getDynamicRoutes('http://c1.fmt.dev/api/eav/entity_types')
}
})
For better code structure and readability, move router definition to separate file:
In your main file, leave just this code:
// main.js
import Vue from 'vue'
import router from '#/router'
import axios from 'axios'
new Vue({
el: '.v-app',
router,
data () {
return {
page_header: '',
page_header_small: '',
}
},
methods: {
getDynamicRoutes (url) {
axios
.get(url)
.then(this.processData)
.catch(err => console.log(err))
},
processData: ({data}) => {
data.forEach(this.createAndAppendRoute)
},
createAndAppendRoute: route => {
let newRoute = {
path: `/${route.name}`,
component: eav_index,
name: `${route.name}_index`,
props: {entity_type_id: route.id}
}
this.$router.addRoutes([newRoute])
}
},
created () {
this.getDynamicRoutes('http://c1.fmt.dev/api/eav/entity_types')
}
})
And in same folder as main file lies, create subfolder 'router' with 'index.js' within:
// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import item_index from '../../../app/Tenant/Item/Views/Index.vue'
import contact_index from '../../../app/Tenant/Contact/Views/Index.vue'
import eav_index from '../../../app/Tenant/Eav/Views/create.vue'
import eav_create from '../../../app/Tenant/Eav/Views/create.vue'
Vue.use(VueRouter)
export default new VueRouter({
mode: 'history',
linkActiveClass: 'active',
routes: [{
path: '/items',
component: item_index,
name: 'item_index'
}, {
path: '/contact',
component: eav_index ,
name: 'contact_index' ,
props: {entity_type_id: 1}
}]
})
The vue instance is already initiated when you try to add the routes (same problem as in this question: How to use addroutes method in Vue-router? ). You could postpone the vue initalization after the routes are loaded:
//imports and stuff...
axios
.get('http://c1.fmt.dev/api/eav/entity_types')
.then(response => {
for (var i = 0; i < response.data.length; i++) {
var type = response.data[i];
var route = {
path: '/' + type.name,
component: eav_index,
name: type.name + '_index',
props: {
entity_type_id: type.id
},
};
// extend routes array prior to router init
routes.push(route);
}
// init router when all routes are known
const router = new VueRouter({
mode: 'history',
linkActiveClass: 'active',
routes
});
// init vuw instance when router is ready
new Vue({
el: '.v-app',
data(){
return {
page_header: '',
page_header_small: '',
}
},
router, axios
});
})
.catch(error => {
console.log(error)
});