下面的demo是安装了vue-cli脚手架建立项目,按项目默认路径做的。
1、建一个home.vue 文件<template>内容如下:
路径src/ 或者 src/下的其他路径都行,要通过浏览器IP端口访问过来,后续还要定义路由(在第3点)
<template>
<div id='home'>
<bar bartitle="this is a title" barurl="/test" />
<!-- 使用了一个bar 组件,且还向组件传了两个值-->
</div>
</template>
<script>
<!-- 正常使用组件,需要导入组件,并进行注册-->
import topbar from '@/components/topbar.vue'
export default {
data(){
return{
};
},
components:{
// 组件注册 组件名:导入组件包名 如果导入组件名与使用组件名一致,则直接写成 bar 即可
'bar':topbar
}
}
</script>
2、组件 topbar.vue,对应路径和上面组件注册路径一致,/components/topbar.vue
<template>
<div id='top'>
<h1>{{ bartitle }}</h1>
<h1><a :href="barurl" >to the test page</a><h1>
<!-- 点击这个链接,就会进入到 127.0.0.1:8080/test 如果定义了这个路由,将进入到指定组件页面 -->
<!-- barurl 就是通过home.vue的点击传过来的/test -->
<!-- 通过点击路由链接,将会展示指定路由内容到下面的router-view -->
<router-link to="/test/a">routerTestA</router-link>
<!-- 添加路由视图 如果有多个路由视图需要添加name用于区分 -->
<router-view name="childA"></router-view>
</div>
</template>
<script>
export default {
name:"topbar",
// 通过props获取父组件传递过来的值 props多种写法
// props:['bartitle','barurl']
props:{
bartitle:String,
barurl:String
}
}
</script>
这样,实际展示的home.vue就其实导入了topbar.vue的内容。再建一个test.vue,点击“to the test page”就能通过路由配置链接到test.vue去。
为了
(1)能通过地址127.0.0.1:8080/ 或者127.0.0.1:8080/home访问到页面
(2)能使上面topbar组件的“to the test page”能正常链接到127.0.0.1:8080/test
还需要定义路由
3、定义路由
src下面有个默认的main.js,内容如下,是将router路径下的全部文件均导入进来作为路由
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
router下面又有个默认的index.js定义了路由,那么,要能够访问到上面两个地址,index.js 可以改写demo如下
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home.vue'// 导入home.vue 导入有多种方式,这是其一
Vue.use(VueRouter)
const routes = [
{
path: '/',// 通过根路径访问
name: 'home',
component:home
},
{
path: '/test',// 通过/test访问
name: 'test',
component: () => import('../views/test.vue') //导入test.vue 这样写也可以导入
// 还可以设置子路由,嵌套在
children:[{
path: '/test/a',
components: {childA:test}// 如果存在多个路由视图,最好绑定路由视图名称childA
}
,
{
path: '/home',// 通过/home访问
name: 'home',
component:home
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
demo就这样完成。。。
关于子路由,可以看看这篇
https://blog.csdn.net/weixin_45122120/article/details/109177240