发表于: 2019-12-18 22:53:38

1 1493



今天完成的事情:

1.继续学习vue


明天计划的事情:

1.推进任务,学习vue


遇到的问题和收获:

1.路由的默认路径

刚进入页面时,需要直接显示主页,而不是点击后才显示,所以可以多添加一个映射关系。

使用redirect重定向,当进入页面,路径为缺省值时,定向到/home

{
path
:'',
redirect
:'/home'
//redirect重定向,路径为认值时,定向到/home
}


改变路径的方式有两种

url的hash,HTML5的history

默认路径改变是通过哈希值,可以更换为html history。


const router=new VueRouter({
//配置路由和的映射
routes,
mode
:'history'
})

在router里声明模式mode为history


router-link

 

里面的to属性可以指定跳转路径。

tag属性可以指定router-link之后渲染成什么组件,比如

<router-link to="/home" tag="button"></router-link>

可以渲染成按钮。

 

replace属性加入后,点击按钮跳转时,就不能使用浏览器的返回了

<router-link to="/home" tag="button" replace></router-link>

按钮激活时active的名字可以修改


使用active-class可以修改激活后的名字

<router-link to="/home" tag="button" replace active-class="active"></router-link>


如果有多个标签想要修改这样的属性。可以在index.js里的router添加linkActiveClass属性

const router = new VueRouter({
//配置路由和的映射
   
routes,
    mode
: 'history',
    linkActiveClass
:'active'
})


路由代码跳转

比如上面不想用router-link,直接用普通标签。

<button @click="linkHome">AAAA</button>
<
button @click="linkMine">BBBB</button>

 

export default {
    name
: 'App',
    methods
: {
       
linkHome() {
           
this.$router.push('/home')
        },
       
linkMine() {
           
this.$router.push('/mine')
        }
    }
}

则需要在方法中添加this.$router.push或者this.$router.replace。replace不能进行返回。



动态绑定

比如给一个动态的id

在index.js里,routes在/mine后面加上/:useId

{
    path
: '/mine/:useId',
    component
: Mine
}

App.vue输出里面增加数据

data() {
   
return {
        userId
: 'zhangSan'
   
}
}

将数据返回给router-link,使用v-bind绑定,’’内作为一个字符串

<router-link :to="'/mine/'+userId" tag="button" replace>我的</router-link>



还想设置一个参数,获取到动态id时,显示在文本里

 

computed: {
   
userId() {
       
return this.$route.params.userId
    }
}



$router可以调用push、replace等方法,它是index.js里面拿到的router对象。


$route是当前哪个路由处于活跃状态,拿到的就是哪个路由



再使用它

<p>{{userId}}</p>

 

params,参数parameters的缩写。userId是根据路径后面的命名来的




路由的懒加载

即使用到时再加载。当打包构建应用时,js包会变得非常大,影响页面加载。

将不同的路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就非常的高效。


// import Home from "../components/Home";
// import Mine from "../components/Mine";

const Home = () => import('../components/Home')
const Mine = () => import('../components/Mine')

懒加载写法,注释掉的是之前的写法。以后路由的写法都要用懒加载。


好多呀






返回列表 返回列表
评论

    分享到