代码如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>路由初体验</title> 8 <script src="./js/vue2.js"></script> 9 <!-- 1. 引入路由文件 --> 10 <script src="./js/vue-router-3.0.1.js"></script> 11 </head> 12 <body> 13 <div id="app"> 14 <ul> 15 <!-- 在 vue 中使用router-link 去做跳转,他有一个to属性,to属性的属性值必须和path中路径对应。router-link将来会被渲染成 a 标签,to属性将会被
渲染成 a 标签的 href 属性,但他的值前面会加一个 # ,变为锚点 --> 16 <li><router-link to="/index">首页</router-link></li> 17 <li><router-link to="/product">水果</router-link></li> 18 <li><router-link to="/product">蔬菜</router-link></li> 19 <li><router-link to="/product">肉类</router-link></li> 20 </ul> 21 <!-- 6. 使用 router-view 挖一个坑,路径匹配到的组件都会渲染到这个坑里面--> 22 <router-view></router-view> 23 </div> 24 <script> 25 // 2. 创建需要的路由组件 26 var index = Vue.component(‘index‘, { 27 template: ‘<div>首页</div>‘ 28 }) 29 var product = Vue.component(‘product‘, { 30 template: ` 31 <div> 这里显示产品的编号</div> 32 ` 33 }) 34 //3. 创建路有对象,在这个对象里配置路由规则 这里用router(名字可随意取)这个变量来接收vueRouter(名字固定不可改变)路由对象 35 var router = new VueRouter({ 36 //4. 通过 routes 属性配置路由规则,它是一个数组,数组中放的是对象,每一个对象对应一条路由规则,而且每个对象里都包含 name(表示路由规则的名称)
path(表示路径) component(表示路径对应的组件) 三个参数 37 routes: [ 38 {name: ‘index‘, path:‘/index‘, component: index}, 39 {name: ‘product‘, path:‘/product‘, component: product} 40 ] 41 }) 42 var vm = new Vue({ 43 el: ‘#app‘, 44 // 5. 在 vue 实例中注入路由, 这样整个程序都拥有路由了 45 router: router, // 用 ES6 的语法可以简写为 router, 46 data: { 47 48 } 49 }) 50 </script> 51 </body> 52 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>动态创建组件</title> 8 <!-- 1. 引入 vue 文件 --> 9 <script src="./js/vue2.js"></script> 10 </head> 11 <body> 12 <div id="app"> 13 <ul> <!-- 注意:在点击事件后面的变量componentId 赋值的时候 即组件的名称一定加上引号 --> 14 <li @click="componentId=‘index‘"><a href="#">首页</a></li> 15 <li @click="componentId=‘product‘"><a href="#">水果</a></li> 16 <li @click="componentId=‘product‘"><a href="#">蔬菜</a></li> 17 <li @click="componentId=‘product‘"><a href="#">肉类</a></li> 18 </ul> 19 <component :is="componentId"></component> 20 <!-- 3. 因为我们想要点击相应的项,然后显示对应的组件,我们只需要动态的显示 is 后面的值(组件的名称),所以is后面的值用一个变量 componentId 来保存到数据 data 中,默认开始为空--> 21 <!-- 4. 把componentId这个变量绑定到is 属性上 即:is="componentId" --> 22 <!-- 5. 给每个 li 标签绑定点击事件 并且在点击的时候执行显示对应的组件 即变量componentId的值等于对应的组件的名称--> 23 </div> 24 <script> 25 // 2. 创建需要的组件 26 //创建首页组件 27 Vue.component(‘index‘,{ 28 template: ‘<div>首页</div>‘ 29 }) 30 // 创建产品的组件 31 Vue.component(‘product‘, { 32 template: ‘<div>这里是产品编号</div>‘ 33 }) 34 var vm = new Vue({ 35 el: ‘#app‘, 36 data: { 37 componentId: ‘‘ 38 } 39 }) 40 </script> 41 </body> 42 </html>
原文:https://www.cnblogs.com/lirun-rainbow/p/10357523.html