Laravel Vue.js - 包含vue-router的最简单方法?

时间:2017-07-22 10:12:46

标签: javascript php laravel vue.js vue-router

在bootstrap.js中,我有这个:

window.Vue = require('vue');
window.events = new Vue();

现在我想使用vue-router纯粹是为了访问这个。$ route。最简单的方法是什么?我试图遵循官方文档,但它与laravel的内容有很大不同:

const app = new Vue({
router
}).$mount('#app')

谢谢!

3 个答案:

答案 0 :(得分:1)

首先安装vue-router

然后在router.js中创建一个新文件resources/assets/js并将此代码放入其中。

import Router from 'vue-router'

Vue.use(Router)

/*
   Make sure your pages components are inside `resources/assets/js/pages` folder
*/
const Home = require('./pages/Home.vue')
const Hello = require('./pages/Hello.vue')
const NotFound = require('./pages/NotFound.vue')

let router = new Router({
    mode: 'history',
    routes: [
    {
        path: '/',
        name: 'home',
        component: Home
    }, {
        path: '/hello',
        name: 'hello',
        component: Hello
    }, {
        path: '*',
        component: NotFound
    }, ]
})

export default router

现在转到app.js文件并插入此代码:

import Vue from 'vue'
import router from './router.js'

const app = new Vue({
    el: '#app',
    router, // Add this to your Vue instance
    //...
})

然后创建您的网页(在这种情况下为Home.vueHello.vueNotFound.vue。)

答案 1 :(得分:0)

app.js中的

import VueRouter from 'vue-router';
window.Vue = require('vue');
window.Vue.use(VueRouter);
import router from './config/routes';
const app = new Vue({
    el: '#app',
    router,
});

你可以将路由定义的代码解压缩到./config/routes.js,见下面的例子:

import VueRouter from 'vue-router';
const routes = [
    {path: '/', redirect: '/app/articles'},
    ...
];

const router = new VueRouter({routes});
export default router;

答案 2 :(得分:0)

以下是使laravel路线和vue路线协同工作的步骤:

1。定义您的Vue布局

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Project</title>
    <link rel="stylesheet" href="/css/app.css">
</head>

<body>
    <div id="app"></div>
    <script src="/js/app.js"></script>
</body>
</html>

2。定义您的Laravel路由以使vue-router处理url

Route::any('{all}', function(){
    // welcome view should extend layout defined in step #1
    return view('welcome');
})->where('all', '.*');

3。用vue-router设置vue

routes.js

import DashboardPage from './components/dashboard/dashboard.vue'
import SignupPage from './components/auth/signup.vue'
import SigninPage from './components/auth/signin.vue'

export const routes = [
  { path: '/signup', component: SignupPage },
  { path: '/signin', component: SigninPage },
  { path: '/dashboard', component: DashboardPage },
  { path: '*', redirec: '/' }
];

router.js

import VueRouter from 'vue-router';
import { routes } from './routes';

export const router = new VueRouter({
  routes,
  mode: 'history'
});

export default router

main.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import { router } from './router'

Vue.use(VueRouter);

new Vue({
  router: router,
  render: h => h(App)
}).$mount('#app')