How to use controller in vuejs2 - javascript

Hi I start using vuejs2 with project based on laravel backend
in my vuejs2, I did this code in the file routes.js
export default new VueRouter({
routes: [{
path: '/test',
component: Test
},
{
path: '/settings',
component: Settings
},
// users
{
path: '/users/create',
component: Create
},
// end users
],
});
Now in the line { path: '/users/create', component: Create}, I'm wondering how could I go to controller first and the controller redirect me to the component
like in laravel first think I write in route.php and calling a function in the controller and the controller redirect me to the view vile
what I found that's from the route I go to the component
but I need to do things before redirecting me to the component
thanks a lot.

. There is a guard available with VueRouter to perform checks. It is called BeforeEach(). What this will do is before resolving the next request in the pipeline it will check for the conditions to be satisfied.
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
if(some_condition){
next();
} else if(some_error){
next('/'); //rerouting
}
})
You can check this documentation : https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
Here you can push the route you want to include in the pipeline using next() and
change it according to your conditions.

Related

Nuxt Dynamic routes returns 404 after static generation

guys. I have a shop page with two params: page and sort. like below:
example.com/shop/
example.com/shop/page/2/
example.com/shop/sort/newest/
example.com/shop/sort/oldest/page/2/
this is my route configs:
router: {
extendRoutes(routes, resolve) {
routes.push(
{
path: '/shop/sort/:sort/page/:page(\\d+)',
component: resolve(__dirname, 'pages/shop/index.vue'),
name: 'shop-sort-page',
},
{
path: '/shop/sort/:sort',
component: resolve(__dirname, 'pages/shop/index.vue'),
name: 'shop-sort',
},
{
path: '/shop/page/:page(\\d+)',
component: resolve(__dirname, 'pages/shop/index.vue'),
name: 'shop-page',
},
)
}
},
Now, after i generate my website, Nuxt doesn't generate sort pages. when i go to /sort/ or /sort/oldest/page/2/ it returns 404.
what do I need to do?
if I need to generate all these pages by myself, then what are these routes.push() used for?
I also want to add "name" and "filter" params. you see generating a dynamic route for all these parameters is impossible. what can I do?
thanks.
Im using Nuxt 2, by official doc, you need to add route for each parameter https://nuxtjs.org/docs/configuration-glossary/configuration-generate/#routes
For workaround solution, I may create a redirect page for dynamic page and url is
example.com/shop/redirect?page=2&sort=newest
In redirect page:
mounted(){
const p_page= this.$route.query.page
const p_sort = this.$route.query.sort
this.$router.push(`/shop/sort/${p_sort}/page/${p_page}`)
}

Problem with Voyager admin panel routing and Vue js router in laravel

I`m developing locally SPA application using Vuejs V2 in Laravel V8 framework.
My routes/web.php file have this codes:
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
});
//for disallow accessing route from anywhere alse than api
Route::get('/{any?}', function () {
return view('welcome');
})->where('any', '^(?!api\/)[\/\w\.\,-]*');
Auth::routes();
Here is my routes.js file inside resources/js folder
import VueRouter from "vue-router";
const routes = [
{
path: "*",
component: require("./components/PageNotFound").default,
name: "PageNotFound"
},
{
path: "/",
component: require("./components/Home").default,
name: "home"
},
// other routes
];
const router = new VueRouter({
mode: "history",
linkActiveClass: "active",
routes
});
export default router;
My problem is that i cant access Voyager http://127.0.0.1:8000/admin route in browser and redirects me to home page!
My Voyager installed successfully and before installing that i was developing frontend features so i have a lot routes in my routes.js file.
My question is how i can except Voyager admin group route in web.php or any other solutions maybe?!
I solved the problem by stopping serve then start that, worked for me and i can now see admin panel.

Fetch Lumen controller result as Vue.js component

I'm actually trying to build a SPA (single page application) with Lumen as PHP framework and Vue.js as Javascript framework. The reason I use Lumen is because I provide some API that are not available within the SPA. I'm using vue-router to route all my page within the SPA. My question here is: is this possible to call a Lumen controller and get the result (blade vue) into a component for Vue.js?
I've searched the entire web for some help about my issue but, since I am not very used to code with vue.js, I didn't found what I need.
Here's what my app.js look for the moment:
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const Foo = {
template: '<div>foo</div>'
}
const Bar = {
template: '<div><span>bar</span></div>'
}
const router = new VueRouter({
mode: 'history',
base: '/',
routes: [
{
path: '/foo',
component: Foo
},
{
path: '/bar',
component: Bar
}
]
});
new Vue({router}).$mount('#app');
But actually, I really want something like that:
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
base: '/',
routes: [
{
path: '/foo',
component: './user/' // Calling controller expo as GET method (default action would be index()) and retreiving the blade vue for the vue.js component
},
{
path: '/bar',
component: './expo/' // Calling controller expo as GET method (default action would be index()) and retreiving the blade vue for the vue.js component
}
]
});
new Vue({router}).$mount('#app');
Thank you for your help. If you have any other solution for my problem, I'll be happy to hear them. I don't mind using other PHP framework or Javascript framework but, I this is possible with Lumen and Vue, I still wish to continue with them.

WebSocket is always pending cause page to stuck

My front end project is using Vue framework with vue-router to control page route.
In router.js file I declare a new Router variable as:
const router = new Router({
routes: [
{
path:'/',
name:'loginComponent',
component:loginComponent,
},
{
path: '/home',
name: 'home',
component: home,
},
]
});
However, When app runs at route part (this.$router.push('/home');), it sucks forever...
Chrome console shows that a file called WebSocket is always pending, which is the main cause I think.
How can I solve this problem, thanks in advance.

Remove the # hash from URL when using Vue.js in Laravel Homestead

I have a Laravel 5.2 setup running in Homestead and using Vue.js router to build an SPA. I'm trying to completely remove the #hash from the URL which I know can be done, but I keep getting errors:
I've added rewrite ^(.+)$ /index.html last; to my vhosts file in Homestead:
server {
listen 80;
listen 443 ssl;
server_name app.myproject.dev;
root "/home/vagrant/Code/vibecast/app.myproject.com/public";
rewrite ^(.+)$ /index.html last;
index index.html index.htm index.php;
charset utf-8;
...
}
When I restart and open a page I get a 500 Internal Server Error.
Is there anything I need added to routes in Laravel?
var router = new VueRouter({
hashbang: false,
history: true,
linkActiveClass: "active"
})
I can get it working without the #hash (or the modified hosts file) when navigating around, but fails when I reload a page.
You can make Vue Router and Laravel Router work together nicely by making the following changes:
At the end of your routes/web.php add the next lines:
Route::get('{path}', function() {
return view('your-vuejs-main-blade');
})->where('path', '.*');
You need to add this at the end of file because you need to preserve the previously declared laravel routes in order to work properly and not be overwritten by the 404 page or vue-router's paths.
In your Vue router's config use the following:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
let router = new Router({
mode: 'history', //removes # (hashtag) from url
base: '/',
fallback: true, //router should fallback to hash (#) mode when the browser does not support history.pushState
routes: [
{ path: '*', require('../components/pages/NotFound.vue') },
//... + all your other paths here
]
})
export default router
However, when navigating between laravel and vue-router, you need to keep in mind that leaving vue-router's page to a laravel page you must use a window.location.href code, an <a> tag or some sort of programmatic navigation in order to fully exit Vue-router's instance.
Tested this with Laravel 5.5.23, Vue 2.5.9, Vue-Router 3.0.1
I've managed to find a solution, via Matt Stauffer's demo app. First, no need to update vhosts file. Just need to update the SPA/Vue.js route in routes.php to:
Route::get('/{vue?}', 'AppController#spa')->where('vue', '[\/\w\.-]*');
If you have an admin panel and do not want to consider its prefix
Route::get('/{vue?}', 'AppController#spa')->where('vue','^(?!panel).*$');
And of course initialise the Vue.js router like so:
const router = new VueRouter({
history: true,
hashbang: false,
linkActiveClass: 'active'
})
router.mode = 'html5'
Ref: https://github.com/mattstauffer/suggestive/blob/master/app/Http/routes.php#L9
You need to set the router mode to html5 RE: http://vuejs.github.io/vue-router/en/api/properties.html
So your new code would be like:
var router = new VueRouter({
hashbang: false,
history: true,
linkActiveClass: "active"
})
router.mode = 'html5'
export default new Router({
mode: 'history', // https://router.vuejs.org/api/#mode
linkActiveClass: 'active',
})
Laravel router
Route::any('{all}', function () {
return view('welcome');})->where(['all' => '.*']);
Vue-router
export default new Router({
routes: [
{ path: '/', name: 'Home', component: HomeView },
{ path: '/category', name: 'Category', component: CategoryView },
{ path: '/topic', name: 'Topci', component: TopicView }
],
mode: 'history'
})
Add the below line to your Laravel web.php
Route::get('/{vue?}', 'App\Http\Controllers\AppController#index')->where('vue', '[\/\w\.-]*');
Vue-Router
const router = new VueRouter({
mode: 'history',
routes,
})

Categories