我正在尝试将Vue路由器集成到我的Vue项目中。
为此,我安装了npm install vue-router@4
包。
在我的main.js
中,我像这样集成路由器:
import Vue from 'vue'
import App from './App.vue'
// Router
import * as VueRouter from 'vue-router';
import StartNovice from './components/Novice/StartNovice';
const routes = [
{
path: '/novice',
name: 'novice',
component: StartNovice
}
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: routes,
})
Vue.use(VueRouter);
new Vue({
router: router,
render: h => h(App),
}).$mount('#app')
然后我试着在App.vue
中创建一个链接,像这样:
<router-link to="/novice">Link Text</router-link>
<router-view></router-view>
然而,我得到
[Vue warn]: Unknown custom element: <router-link> - did you register the component correctly?
[Vue warn]: Unknown custom element: <router-view> - did you register the component correctly?
好吧,显然我没有!
医生说Make sure to _use_ the router instance to make the whole app router-aware
。因此,我尝试将Vue.use(VueRouter);
更改为Vue.use(router);
,但这使事情变得更糟:
Uncaught TypeError: Cannot set properties of undefined (setting '$router')
我做错了什么?谢谢!
Vue router 4与Vue 3兼容,Vue 3的语法与Vue 2不同:
import {createApp} from 'vue'
import App from './App.vue'
// Router
import * as VueRouter from 'vue-router';
import StartNovice from './components/Novice/StartNovice';
const routes = [
{
path: '/novice',
name: 'novice',
component: StartNovice
}
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: routes,
})
createApp(App).use(router).$mount('#app')
确保安装Vue版本3
看起来你错过了我所说的'拦截'。添加
Route::get('/{vue_capture?}', function () {
return view('index');
})->where('vue_capture', '[/w.-]*');
到你的Web.php。这是一个工作的app.js。有很多设置方法
import './bootstrap';
import { createApp } from 'vue';
import { createWebHistory, createRouter } from "vue-router";
import index from '../components/ComponentName.vue';
const routes = [
{ path: '/', component: index },
]
const router = createRouter({
history: createWebHistory(),
routes
})
const app = createApp({})
.use(router)
.mount('#app');
确保在index.php中有一个最外面的div, id="app"然后,在你想要路由组件出现的地方。
,
<div id="app">
<div class="w-screen h-screen">
<router-view></router-view>
</div>
</div>
记住w-screen -screen是顺风。希望对你有帮助。