创建项目
$ vue create router-app
添加 vue-router
$ cd router-app
$ npm install vue-router
启动项目
$ npm run serve
创建 Home 组件
src/components/Home.vue
<template>
<div>
<h1>主页</h1>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data () {
return {
msg: "我是 home 组件"
}
}
}
</script>
创建 About 组件
src/components/About.vue
<template>
<div>
<h1>关于我们</h1>
<p>{{aboutMsg}}</p>
<p><button @click="jump()">go home</button></p>
</div>
</template>
<script>
export default {
data () {
return {
aboutMsg: '我是 about 组件'
}
},
methods:{
jump(){
this.$router.push("home")
}
}
}
</script>
创建 src/router.js
import Vue from "vue";
import VueRouter from "vue-router";
// 引入组件
import home from "@/components/Home.vue";
import about from "@/components/About.vue";
// 要告诉 vue 使用 vueRouter
Vue.use(VueRouter);
const routes = [
{
path:"/home",
component: home
},
{
path: "/about",
component: about
}
]
var router = new VueRouter({
routes
})
export default router;
src/App.vue 中添加路由导航
<template>
<div id="app">
<header>
<router-link to="/home">主页</router-link>
<router-link to="/about">关于我们</router-link>
</header>
<!-- 对应组件内容 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
}
</script>
src/main.js 中引入 router
import Vue from 'vue'
import App from './App.vue'
import router from "./router.js"
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
网友评论