Vue路由编程式导航以及hash模式

import Vue from 'vue';
import App from './App.vue';


//引入公共的scss   注意:创建项目的时候必须用scss

import './assets/css/basic.scss';   




//请求数据


import VueResource from 'vue-resource';
Vue.use(VueResource);




import VueRouter from 'vue-router';

Vue.use(VueRouter);

//1.创建组件


import Home from './components/Home.vue';

import News from './components/News.vue';

import Content from './components/Content.vue';



//2.配置路由   注意:名字

const routes = [
  { path: '/home', component: Home },
  { path: '/news', component: News,name:'news' },

  { path: '/content/:aid', component: Content },   /*动态路由*/

  { path: '*', redirect: '/home' }   /*默认跳转路由*/
]


//3.实例化VueRouter  注意:名字

const router = new VueRouter({
  mode: 'history',   /*hash模式改为history*/
  routes // (缩写)相当于 routes: routes
})




//4、挂载路由

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})


//5 <router-view></router-view> 放在 App.vue
<template>
    <!-- 所有的内容要被根节点包含起来 -->
    <div id="home">    
       我是首页组件


        <button @click="goNews()">通过js跳转到新闻页面</button>
       
    </div>
</template>


<script>
    export default{
        data(){
            return {               
               msg:'我是一个home组件'
             
            }
        },
        methods:{

            goNews(){


                // 注意:官方文档写错了


                //第一种跳转方式

                // this.$router.push({ path: 'news' })


                // this.$router.push({ path: '/content/495' });







                //另一种跳转方式

                    //   { path: '/news', component: News,name:'news' },


                    // router.push({ name: 'news', params: { userId: 123 }})


                    this.$router.push({ name: 'news'})


                

            }
        }
    }

</script>

<style lang="scss" scoped>
    
</style>

猜你喜欢

转载自www.cnblogs.com/loaderman/p/11058382.html