router not defined when calling inside a vuex action - laravel

Am using Vuex in my Laravel app and for some reason, I cannot do route.push inside an action.
My app.js:
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router'
import { routes } from './routes'
import store from './store/store'
Vue.use(VueRouter)
Vue.component('app-component', require('./App.vue').default);
Vue.component('appRegister', require('./components/User/Register.vue').default);
Vue.component('appLogin', require('./components/User/Login.vue').default);
const router = new VueRouter({
mode: 'history',
routes
})
const app = new Vue({
el: '#app',
router,
store
});
Inside my Login controller, I have a method called login which looks like the following:
login(){
this.$store.dispatch('login', this.user);
}
Then my login action looks like this:
login: ({commit}, user) => {
state.users.map(u => {
if(u.email == user.email){
router.push('/');
}
});
}
When I click on the button, I see the following error in the console:
[Vue warn]: Error in v-on handler: "ReferenceError: router is not defined"
Note, if I do the following inside the Component method, it works fine:
login(){
this.$router.push('/');
}
How can I do the route push inside the vuex action?
I looked at this answer here but it does not seem to solve my problem.
I imported vue-router inside app.js

You have to define your vue router in your login controller or import your router into your login controller.

Related

Vue js router not loading page if i'm passing token from router.js

I'm using vue js with laravel api . i have defined router for forget password page in url i'm passing token . when i'm passing token then page not loading its coming not found.
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Router from 'vue-router'
import ResetPasswordForm from './pages/ResetPasswordForm'
Vue.use(Router)
const routes = [{
path: 'reset-password/:token',
name: 'ResetPasswordForm',
component: ResetPasswordForm
}]
export default new Router({
mode: 'history',
routes
})
web.php
Route::any('{slug}', function () {
return view('welcome');
});
please help me how to fixed out this issue.

Vue.js router view no components?

I am trying to make a vue SPA using vuex, vue-router & laravel for backend. I was separating our data on our app.js to try to reduce clutter and keep our code neat. When everything on one page it works as intended, loading the routes in the router. But when we separate the code to make it more modular into: app.js, boostrap.js, routes.js, and store.js
The components aren't loading in our router-view and we are able to see our RouterLink
app.js
// Require the bootstrapper
require('./bootstrap');
// Grab imports
import Store from './store';
import Router from './routes';
// Views
import App from './views/App';
// Create the application
const app = new Vue({
el: '#heroic',
components: { App },
store: Store,
router: Router
});
boostrap.js
// Imports
import Vue from 'vue';
import Axios from 'axios';
import Swal from 'sweetalert2';
// Add to window
window.Vue = Vue;
window.Axios = Axios;
// Add Axios headers
window.Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.Axios.defaults.headers.common['Authorization'] = 'Bearer ' + 'token';
window.Axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
routes.js
// Imports
import Vue from 'vue';
import VueRouter from 'vue-router';
import Store from './store';
// Set to use
Vue.use(VueRouter);
// Views
import Hello from './views/Hello';
import Home from './views/Home/';
import UserIndex from './views/UserIndex';
// Create our routes
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/hello',
name: 'hello',
component: Hello,
},
{
path: '/users',
name: 'users.index',
component: UserIndex,
}
];
// Create the router
const router = new VueRouter({
mode: 'history',
routes: routes,
scrollBehavior (to, from, saved) {
if (saved) {
return saved;
}
return { x: 0, y: 0};
}
});
// Before every request
router.beforeEach((to, from, next) => {
});
// After every request
router.afterEach((to, from, next) => {
});
// Export
export default router;
hello.vue
<template>
<div class="row row-cards row-deck">
<div class="col-lg-4 col-md-6">
<p>Hello World!</p>
</div>
</div>
</template>
store.js
// Imports
import Vue from 'vue';
import Vuex from 'vuex';
import PersistedState from 'vuex-persistedstate';
import Cookie from 'js-cookie';
// Set use
Vue.use(Vuex);
// Create our store
const store = new Vuex.Store({
state: {
auth: [{
id: 1,
username: '',
motto: '',
rank: 1,
permissions: [],
token: ''
}],
users: [],
},
mutations:{
},
actions: {
},
getters: {
}
});
// Export
export default store;
The expected result is that when I visit the "/hello" route it would show the information that says "Hello world!" that is within the Vue file specified as the component in the routes section of the router. Instead using my Vue DevTools I get the following with no Hello world on the page.
https://i.pathetic.site/chrome_99Mbxf7f0c.png
My guess is the router is stuck waiting for the beforeEach (and also possibly afterEach) hook to be resolved. You need to call next().
Also unrelated, but if you’re using modules then you shouldn’t need to assign stuff on window.

laravel + vue router cannot get parameters from url

I try to get parameters from url
let's say url contains:
localhost:8000/blog?q=hello
I want to grab hello to trigger function call
What I had declare in app.js in laravel webpack:
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: []
})
const app = new Vue({
router
});
export default app;
In blog page, I try to extract the parameter from url
new Vue ({
el: "#blog-content",
},
mounted: function() {
q = this.$route.query.q
console.log(q)
}
)
I npm run dev to compile and run the blog page it show error:
TypeError: Cannot read property 'query' of undefined
what is wrong? I am sure that Vue Router is properly installed in the application.
I think that the blog page that you use is not correct.
You recreate another Vue instance and in that case that new instance doesn't have a router passed to it. So I think that's why this.$router is undefined.
Also you don't pass the view Component to your router so it doesn't know what to look for with the specific url.
Here's your app.js file corrected
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import Blog from './views/Blog';
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/blog',
name: 'blog',
component: Blog
},
]
});
The blog view page template : views/Blog.vue
<template>
<div class="wrapper">
My blog page
</div>
</template>
<script>
export default {
data() {
return {
myvariable : ''
}
},
mounted() {
let q = this.$route.query.q;
console.log(q);
},
};
</script>
Now it should works correctly :)
Edit : Also you don't need to export the app variable in your app.js
Remove the following line export default app; at the end of the file

Vue.js Google / Microsoftgraph login

I have a Laravel app and I am using vue.js and vue-authenticate to have a user login with their Microsoft account. The vue.js app is living under a laravel route not Laravel home page i.e. if the homepage route is / then the vueapp route is /vueapp.
On the vueapp's home page I have the Login with Microsoft button configured. In my vue app the base url is set to mydomain/vueapp. I can successfully authorize the app with my Microsoft account but then instead of being able to see a success message and a token, I see the following error:
Error: Request failed with status code 405
I have Axios and Vuex installed and my vue routes are supported in the hash mode instead of history because of some weird laravel issue.
Update: I am seeing a similar issue with Google. It seems like something happens when the URI is redirected.
Update: Below is my code:
For my component:
<script>
import store from '../store'
import axios from 'axios'
export default{
data () {
return {
}
},
methods: {
authenticate: function (provider) {
console.log("Login Started" + provider);
this.$auth.authenticate(provider).then((response) => {
console.log("Login Successful " + response);
}).catch(error => {
console.log("error occured ");
console.log(error);
})
}
},
}
</script>
My HTML ---
auth Live
auth Google
In my app.js
import Vue from 'vue'
import lodash from 'lodash'
import VueLodash from 'vue-lodash'
import VueAxios from 'vue-axios'
import VueAuthenticate from 'vue-authenticate'
import Vuex from 'vuex'
import App from './App.vue'
import router from './router'
import axios from 'axios'
Vue.use(VueLodash, lodash)
Vue.use(require('vue-moment'));
import vmodal from 'vue-js-modal'
Vue.use(vmodal, {
dialog: true,
dynamic: true,
})
import Toasted from 'vue-toasted';
Vue.use(Toasted, 'top-center')
Vue.use(VueAxios, axios)
Vue.use(Vuex)
import VueAuthenticate from 'vue-authenticate'
Vue.use(VueAuthenticate, {
baseUrl: 'https://www.mywebsite.com', // Your API domain
providers: {
live: {
clientId: 'My Mcirosoft key',
redirectUri: 'https://www.mywebsite.com/auth/live' // Your client app URL
},
google: {
clientId: 'mygooglekey.apps.googleusercontent.com',
redirectUri: 'https://www.mywebsite.com/auth/google'
}
}
})
In laravel - I have the following routes. Webapp is the folder where vue app lives and it uses the hash mode for routing not history.
Route::get('webapp/{path?}', function () {
return View::make('app');
})->where( 'path', '([A-z\d-\/_.]+)?' );
Route::get('auth/live', function () {
return View::make('app');
});
Route::get('auth/google', function () {
return View::make('app');
});

Vue <template> in a .vue file with Lodash

In my .vue file within my template section I have:
<a v-bind:href="'javascript:artist(\'' + _.escape(artist) + '\')'">
which is using the Lodash function _.escape. This generates a string of errors the first of which is:
[Vue warn]: Property or method "_" is not defined on the instance but referenced during
render.
However in the same file in the script section of the component I am happily and successfully using a range of Lodash functions.
This is a Laravel app and in my app.js file I have this code:
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router';
window.Vue.use(VueRouter);
import lodash from 'lodash';
Object.defineProperty(Vue.prototype, '$lodash', { value: lodash });
import SearchHome from './components/search.vue';
const routes = [
{
path: '/',
components: {
searchHome: SearchHome
}
},
]
const router = new VueRouter({ routes })
const app = new Vue({ router }).$mount('#app')
Can anyone please help me?
Try to use a computed value instead. This will improve readability.
Avoid complex operation in a binding.
<a :href="artistLink">
And in the script
import _ from 'lodash'
export default {
computed: {
artistLink () {
return 'javascript:artist(\'' + _.escape(this.artist) + '\')'
}
}
}

Resources