Vue-router安装及使用&切换

Vue-router安装及使用

1、安装:npm install vue-router或cnpm install vue-router或yarn add vue-router
2、在新建router.js中引用如下代码(router.js建立在src文件夹下)

importVuefrom'vue'
importVueRouterfrom'vue-router'
Vue.use(VueRouter)

3、在src中新建view文件夹,在view新建例如:Home文件夹,在文件夹中新建index.vue

<template>
<divid="home">
<Content/>
</div>
</template>
<script>
	import Content from "../../components/Content.vue"
	export default{
    
    
	name:"index",
	data(){
    
    
	  return{
    
    
	  }
	},
	components:{
    
    
	  Content,
	},
	methods:{
    
    
	}
}
</script>

<style scoped>
</style>

4、在router.js中设置如下两步

import Home from './views/Home/'

export default new VueRouter({
    routes:[
        {
            path:'/',
            redirect:'/home'//设置默认指向
        },
        {
            path:'/home',
            component: Home,
        },
    ]
})

5、在App.vue中的div内引入

<router-view></router-view>

6、在main.js中

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

Vue.config.productionTip = false

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

切换

1.在components中引入切换的文件
在这里插入图片描述
2.配置index.vue

<template>
    <div id="home">
        <Content/>
        <router-link to="/home/text1">
            <span>text1</span>
        </router-link> 
        <router-link to="/home/text2">
            <span>text2</span>
        </router-link> 
        <router-link to="/home/text3">
            <span>text3</span>
        </router-link> 
        <router-view></router-view>
    </div>
</template>

3.配置router.js

import Text1 from './components/Text1'
import Text2 from './components/Text2'
import Text3 from './components/Text3'

export default new VueRouter({
    
    
    routes:[
        {
    
    
            path:'/',
            redirect:'/home'//设置默认指向
            // redirect:'/list'//设置默认指向
        },
        {
    
    
            path:'/home',
            component: Home,
            // Vue中使用children实现路由的嵌套
            // 使用 children 属性,实现子路由,同时,子路由的 path 前面,不要带 / ,
            // 否则永远以根路径开始请求,这样不方便我们用户去理解URL地址
	        children:[
	          {
    
    
	            path: '/',
	            redirect:'/text1',//优先显示
	          },
	          {
    
    
	            path: 'text1',
	            component: Text1,
	          },
	          {
    
    
	            path: 'text2',
	            component: Text2,
	          },
	          {
    
    
	            path: 'text3',
	            component: Text3,
	          }
	        ]
        }
    ]
})

Guess you like

Origin blog.csdn.net/weixin_46261261/article/details/107559464