vue插件与vue路由跳转,传参,重定向

x33g5p2x  于2021-08-23 转载在 Vue.js  
字(4.7k)|赞(0)|评价(0)|浏览(615)

十三 插件

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:

添加全局方法或者 property。如:vue-custom-element

添加全局资源:指令/过滤器/过渡等。如 vue-touch

通过全局混入来添加一些组件选项。如 vue-router

添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

13.1 插件的使用

Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象

插件开发

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或 property
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件选项
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}

使用插件

// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)

或者

Vue.use(MyPlugin, { someOption: true })

13.2 vue-router

参考地址: https://router.vuejs.org/zh/api/

复制demo目录重命名为 vue-route;

npm install --save vue-router

在views目录下新建index.vue

<template>
    <div>
        <h1>首页</h1>
    </div>
</template>
<script>
    export default {

    }
</script>

在views目录下新建about.vue

<template>
    <div>
        <h1>介绍页</h1>
    </div>
</template>
<script>
    export default {

    }
</script>

在main.js修改内容如下,即路由配置

import Vue from 'vue';
import App from './app.vue';
import VueRouter from 'vue-router';

Vue . use(VueRouter) ;
new Vue({
    el: '#app',
    render: h => {
        return h(App)
    }
});

// 异步路由配置
const Routers = [
    {
        path: '/index',
        component: (resolve) => require(['./views/index.vue'], resolve)
    },
    {
        path: '/about',
        component: (resolve) => require(['./views/about.vue'], resolve)
    },
    // 当路径不存在时重定向至首页
    {
        path: '*',
        redirect: '/index'
    }
];
const RouterConfig = {
    // 使用 HTML5 的 History 路由模式
    mode: 'history',
    routes: Routers
};
const router = new VueRouter(RouterConfig);

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

webpack.json内容修改如下,使其支持 history模式

"dev": "webpack-dev-server --open --history-api-fallback --config webpack.config.js"

webpack.config.js修改插配置支持异步路由的chunk打包

 plugins: [
        new ExtractTextPlugin({
            filename: '[name].css',
            allChunks: true
        }),
        new VueLoaderPlugin()
    ]

在app.vue中导入router

<template>
    <div>
        <router-view></router-view>
    </div>
</template>
<script>
    export default {
        
    }
</script>

运行 npm run dev 就可以访问多个页面

http://localhost:8080/index

http://localhost:8080/about

13.3路由匹配

在main.js中添加

const Routers = [
    // 
    {
        path: '/user/:id',
        meta: {
            title: '个人主页'
        },
        component: (resolve) => require(['./views/user.vue'], resolve)
    }
];

views 底下添加user.app

<template>
    <div>{{ $route.params.id }}</div>
</template>
<script>
    export default {
        mounted () {
            console.log(this.$route);
        }
    }
</script>

在浏览器输入 http://localhost:8080/user/6666 即即可访问带参数的页面;

13.4 路由跳转

方式一

index.vue 中添加跳转配置<router-link>, 其会被渲染为a标签; to 是一个 props ;

<template>
    <div>
        <h1>首页</h1>
        <router-link to="/about">跳转到 about</router-link>
    </div>
</template>
<script>
    export default {

    }
</script>

props支持的标签如下

  • tag : 指定渲染的标签;<router-link to="/about" tag="li">;
  • replace : 页面无法回退;<router-link to="/about" replace>;

方式二

通过点击事件跳转

<template>
    <div>
        <h1>介绍页</h1>
        <button @click="handleRouter">跳转到 user</button>
    </div>
</template>
<script>
    export default {
        methods: {
            handleRouter () {
                this.$router.push('/user/666');
            }
        }
    }
</script>

$route其它用法

  • this.$router.go(2); 后退前2页;
  • this.$router.replace('/user/666'); 等同于<router-link replace>;

地址:https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html

复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化) $route 对象:经常使用在$router.push 在同一页面时,路由无法刷新的情况

const User = {
  template: '...',
  watch: {
    $route(to, from) {
      // 对路由变化作出响应...
    }
  }
}

或者使用 2.2 中引入的 beforeRouteUpdate导航守卫

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

13.5 嵌套路由

比如 home的框架主菜单下有多级子菜单,就需要使用子路由跳转;在children中定义子路由

{
      path: '/home',
      meta: { title: '主页' },
      component: (resolve) => require(['@/views/system/home'], resolve),
      children: [
        {
          path: '/index',
          meta: { title: '首页' },
          component: (resolve) => require(['@/views/system/index'], resolve)
        }
 }       

相应的需要在home.vue中 使用 </router-view> 进行路由跳转;

<div class="home">
      <router-view></router-view>
</div>

13.6 路由重定向

访问 a 时将重定向到路由b;

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})

路由别名

访问 b 时 实际上访问的是路由a,但显示的时候还是 b

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

13.7 修改标题

原生的js中使用 window . document.title 修改页面标题,vu-router中使用导航钩子(beforeEach,afterEach)在路由即将改变前后触发;

main.修改内容如下

在每个path前面添加meta信息;

   {
        path: '/user/:id',
        meta: {
            title: '个人主页'
        },
        component: (resolve) => require(['./views/user.vue'], resolve)
    }

添加导航钩子函数信息;

router.beforeEach((to, from, next) => {
    window.document.title = to.meta.title;
    next();
});
// 跳转页面后滚动条返回顶部
router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);
});
  • to 表示即将打开的路由对象;
  • from 表示即将离开的路由对象;
  • next 表示调用该方法后才能进入下一个钩子函数,即放行;

登陆判定跳转示例:

router .beforeEach ((to,from , next) => {
if (window.localStorage.getltem ('token')) {
    next ();
    } else {
    next ('/login');
    }
});    

相关文章