VUE进阶(路由等)

vue2.0+elementUI构建单页面后台管理平台: http://www.cnblogs.com/dmcl/p/6722315.html
初级教程:http://www.cnblogs.com/dmcl/p/6137469.html

VUE进阶

自定义指令

http://cn.vuejs.org/v2/guide/custom-directive.html#简介

// 注册一个全局自定义指令 v-focus
Vue.directive('focus', {
  // 当绑定元素插入到 DOM 中。
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})

使用 <input v-focus>


路由

文档来自:http://router.vuejs.org/zh-cn/

  • 简单路由示例
<head>
    <meta charset="UTF-8">
    <title>路由</title>
    <script src="//cdn.bootcss.com/vue/2.0.3/vue.js"></script>
    <script src="https://unpkg.com/vue-router@2.0.3"></script>
</head>
<body>
<div id="app">
    <h1>Hello App!</h1>
    <p>
        <!-- 使用 router-link 组件来导航. -->
        <!-- 通过传入 `to` 属性指定链接. -->
        <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
        <router-link to="/foo">Go to Foo</router-link>
        <router-link to="/bar">Go to Bar</router-link>
    </p>
    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
</div>
<script>
    // 0. 如果使用模块化机制编程, 要调用 Vue.use(VueRouter)
    // 1. 定义(路由)组件。可以从其他文件 import 进来
    const Foo = { template: '<div>foo</div>' };
    const Bar = { template: '<div>bar</div>' };

    // 2. 定义路由映射 
    // 每个路由应该映射一个组件。 其中"component" 可以是通过 Vue.extend() 创建的组件构造器,或者,只是一个组件配置对象。
    const my_routes = [
        { path: '/foo', component: Foo },
        { path: '/bar', component: Bar }
    ];

    // 3. 创建 router 实例,然后传 `routes` 配置 你还可以传别的配置参数, 不过先这么简单着吧。
    const app_router = new VueRouter({
        routes:my_routes // (缩写)相当于 routes: routes
    });

    // 4. 创建和挂载根实例。记得要通过 router 配置参数注入路由,从而让整个应用都有路由功能
    const app = new Vue({
        router:app_router
    }).$mount('#app');
    // 现在,应用已经启动了!
</script>

对应的路由匹配成功,将自动设置 class 属性值 .router-link-active

  • 组件嵌套
<div id="app2">
    <p>
        <router-link to="/user/foo">/user/foo</router-link>
        <router-link to="/user/foo/profile">/user/foo/profile</router-link>
        <router-link to="/user/foo/posts">/user/foo/posts</router-link>
    </p>
    <router-view></router-view>
</div>
<script>
    const User = {
        template: `
    <div class="user">
      <h2>User {{ $route.params.my_id }}</h2>
      <router-view></router-view>
    </div>
  `
    };
//上面的$route.params.my_id,my_id是匹配的参数,是显示文本 与路由无关
    const UserHome = { template: '<div>Home</div>' };
    const UserProfile = { template: '<div>Profile</div>' };
    const UserPosts = { template: '<div>Posts</div>' };

    const router = new VueRouter({
        routes: [
            { path: '/user/:my_id', component: User,
                children: [
                    //
                    { path: '', component: UserHome },
                    // 当 /user/:id/profile 匹配成功, UserProfile 会被渲染在 User 的 <router-view> 中
                    { path: 'profile', component: UserProfile },
                    // 同上
                    { path: 'posts', component: UserPosts }
                ]
            }
        ]
    });
    const app2 = new Vue({ router }).$mount('#app2')
</script>
  • 编程式导航
    使用 router.push 方法。这个方法会向 history 栈添加一个新的记录
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名路由  name  
router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

replace(location) 类似push 但不改变history
router.go(1) ;
这些方法都是模仿window.historyAPI的window.history.pushState、window.history.replaceState 和 window.history.go
:to和to是一样的

  • 命名路由例子
<div id="app3"></div>
<script>
    Vue.use(VueRouter)
    //组件
    const Home = { template: '<div>This is Home</div>' }
    const Foo2 = { template: '<div>This is Foo</div>' }
    const Bar2 = { template: '<div>This is Bar {{ $route.params.id }}</div>' }
    //路由
    const router3 = new VueRouter({
//        mode: 'history',
        routes: [
            { path: '', name: 'home', component: Home },
            { path: 'foo2', name: 'foo22', component: Foo2 },  // url:  /foo2
            { path: 'bar2/:id', name: 'bar22', component: Bar2 } // url:  /bar2/123
        ]
    });
    new Vue({
        router:router3,
        template: `
    <div id="app3">
      <h1>Named Routes</h1>
      <p>Current route name: {{ $route.name }}</p>
      <ul>
        <li><router-link :to="{ name: 'home' }">home</router-link></li>
        <li><router-link :to="{ name: 'foo22' }">foo</router-link></li>
        <li><router-link :to="{ name: 'bar22', params: { id: 123 }}">bar</router-link></li>
      </ul>
      <router-view class="view"></router-view>
    </div>
  `
    }).$mount('#app3')
</script>
  • 命名视图
    一个视图才有一个组件渲染。一个路由 多个视图就要用多个组件。



    路由写法:
const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

代码参考:https://jsfiddle.net/posva/6du90epg/

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

也可以是 { path: '/a', redirect: { name: 'foo' }}
也可以是(结合ES6箭头函数,箭头函数可参考:https://imququ.com/post/arrow-function-in-es6.html

 { path: '/dynamic-redirect/:id?',
      redirect: to => {
        const { hash, params, query } = to
        if (query.to === 'foo') {
          return { path: '/foo', query: null }
        }
        if (hash === '#baz') {
          return { name: 'baz', hash: '' }
        }
        if (params.id) {
          return '/with-params/:id'
        } else {
          return '/bar'
        }
      }
    },

更多用法 参考:http://router.vuejs.org/zh-cn/essentials/redirect-and-alias.html

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})

before钩子:to 即将进入的 from 当前导航要离开的 next 来执行钩子
after 钩子:
未完待续

原文地址:https://www.cnblogs.com/dmcl/p/6138389.html