Vue2.x路由的步骤

时间:2021-08-06 10:32:20

创建路由步骤:

1.引入vue-router库,可用最新版https://unpkg.com/vue-router

2.创建所需要的组件

3.创建router实例对象

4.在根实例中注册一下 =》方式:router:router

实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-router"></script>
<title>组件化</title>
</head>
<body>
<div id="box">
<router-link to="/home">主页</router-link>
<router-link to="/news">新闻</router-link>
<hr />
<router-view></router-view>
</div> <template id="home">
<div>
<bbb></bbb>
<p>{{msg}}</p>
</div>
</template> <template id="news">
<div>
<bbb></bbb>
<p>{{msg}}</p>
</div>
</template> <template id="bbb">
<div>
<h1>模板</h1>
</div>
</template> <script>
//1.创建组件
var Home=Vue.extend({
template:"#home",
data(){
return { msg:"我是主页模板" };
},
components:{
'bbb':{
template:"#bbb"
}
}
}); var News=Vue.extend({
template:"#news",
data(){
return { msg:"我是新闻模板" };
},
components:{
'bbb':{
template:"#bbb"
}
}
}); //2.创建Router实例对象
var router=new VueRouter(
{
routes:[
{path:"/home",component:Home},
{path:"/news",component:News}
]
}
); //3.创建根实例对象,通过路由配置参数注入路由,让整个应用都有相应的路由地址
var vm=new Vue({
router:router
}).$mount("#box");
</script>
</body>
</html>