Migrating from Vue Router 0.7.x


Only Vue Router 2 is compatible with Vue 2, so if you update Vue, you also need to update Vue Router. This is why we added the details of the migration path in the main documentation.
For a complete tutorial on using Vue Router 2, please see
Vue Router Documentation.


##Directory


#Router initialization



##router.start

replacementThere will no longer be a special API for initializing an app containing Vue Router, which means no longer:

router.start({
  template: '<router-view></router-view>'
}, '#app')

You just need Pass a route attribute to the Vue instance:

new Vue({
  el: '#app',
  router: router,
  template: '<router-view></router-view>'
})

Or, if you are using the runtime-only method:

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

Upgrade method

Run Migration Assistant Find the example where

router.start

is called.


##Route Definition



router.map

##Replace Routes are now defined as an array of routes options
within the router instance. So these routes:

router.map({
  '/foo': {
    component: Foo
  },
  '/bar': {
    component: Bar
  }
})

will be defined in this way:

var router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar }
  ]
})
Considering that traversing objects in different browsers is not guaranteed to use the same property order, the syntax of this array can ensure more accurate Multiple predictable route matching.

Upgrade method

Run Migration Assistant Find router.map is called example.


##router.on##Remove If you need to generate routes through code when the app is launched, you can dynamically push definitions to the routes array to accomplish this operation. For example:

// 普通的路由
var routes = [
  // ...
]

// 动态生成的路由
marketingPages.forEach(function (page) {
  routes.push({
    path: '/marketing/' + page.slug
    component: {
      extends: MarketingComponent
      data: function () {
        return { page: page }
      }
    }
  })
})

var router = new Router({
  routes: routes
})

If you need to add a new route after the router is instantiated, you can change the original matching method of the router to a matching method that includes your newly added route:

router.match = createMatcher(
  [{
    path: '/my/new/path',
    component: MyComponent
  }].concat(router.options.routes)
)

Upgrade methodRun

Migration Assistant

Find the example where router.on is called .


##router.beforeEach changedrouter.beforeEach

now works asynchronously and takes a

next function as its third argument.

router.beforeEach(function (transition) {
  if (transition.to.path === '/forbidden') {
    transition.abort()
  } else {
    transition.next()
  }
})
router.beforeEach(function (to, from, next) {
  if (to.path === '/forbidden') {
    next(false)
  } else {
    next()
  }
})


subRoutes##Change nameFor the sake of consistency between Vue Router and other routing libraries, renamed to children

##Upgrade method

Run Migration Assistant Find an example of the subRoutes

option.

##router.redirect

replaceNow use a route definition option instead. For example, you would update:

router.redirect({
  '/tos': '/terms-of-service'
})
as defined in the

routes

configuration below:

{
  path: '/tos',
  redirect: '/terms-of-service'
}

Upgrade method

Run Migration Assistant Find the example where router.redirect is called.


##router.alias##Replace This is now an option

in the

routing definition for your alias operation. For example, you need to configure:

router.alias({
  '/manage': '/admin'
})
in your routes definition like this:

{
  path: '/admin',
  component: AdminPanel,
  alias: '/manage'
}

If you need to perform multiple alias operations, you can also Use an array syntax to implement:

alias: ['/manage', '/administer', '/administrate']

Upgrade methodRun

Migration Assistant

Find Example of router.alias being called.


Any Route attribute Replace Now any The route attribute must be within the scope of the new meta attribute to avoid conflict with future new features. For example, if you previously defined it like this:

'/admin': {
  component: AdminPanel,
  requiresAuth: true
}

you now need to update it to:

{
  path: '/admin',
  component: AdminPanel,
  meta: {
    requiresAuth: true
  }
}

If you access a property on a route, you will still pass meta . For example:

if (route.meta.requiresAuth) {
  // ...
}

Upgrade methodRun

Migration Assistant

Find any route that is not in meta function Example under domain.


Query array[] syntax in URLRemove

When passing an array to query parameter, the URL syntax is no longer /foo?users[]=Tom&users[]=Jerry, instead, the new syntax is /foo?users=Tom&users=Jerry, at this time $route.query.users will still be an array, but if there is only one parameter in the query: /foo?users=Tom, when accessing the route directly, vue-router will not know that the users we expect is an array. Therefore, consider adding a computed property and replacing it everywhere $route.query.users is used:

export default {
  // ...
  computed: {
    // 此计算属性将始终是个数组
    users () {
      const users = this.$route.query.users
      return Array.isArray(users) ? users : [users]
    }
  }
}


Route matching


Route matching now uses the path-to-regexp package, which will make the job easier than before flexible.


One or more named parametersChange

The syntax has changed slightly, so /category/*tags, for example, should be updated to /category/:tags .

Upgrade method

Run Migration Assistant Find examples of deprecated routing syntax.




## The #v-link directive has been replaced by a new <router-link> component directive, and this part of the work has been completed by the component in Vue 2. This will mean that in any case, if you have a link like this:

<a v-link="'/about'">About</a>

you need to update it to:

<router-link to="/about">About</router-link>

NOTE:

<router-link>Not supportedtarget="_blank"Attribute, if you want to open a new tab, you must use the <a> tag.

Upgrade method

Run

Migration Assistant Find the v-link command Example.


v-link-active

Also because a tag attribute is specified on the <router-link> component And was deprecated. For example, you need to update:

<li v-link-active>
  <a v-link="'/about'">About</a>
</li>
to this:

<router-link tag="li" to="/about">
  <a>About</a>
</router-link>

<a>

tag will become a real link (and the correct link can be obtained Jump), but the activated class will be applied to the external <li> tag.

Upgrade methodRun

Migration Assistant

Find v-link-active Examples of directives


Programming Navigation



##router.go##ChangeFor consistency with the HTML5 History API
,

router.go

has been used as the back/forward navigation, router. push is used to direct special pages.

Upgrade method

Run Migration Assistant and find

router.go

and router.push Example of the instruction being called.


Routing: Modes



##hashbang: false Remove

Hashbangs will no longer As Google needs to crawl a URL, they will no longer be the default option for the hashing strategy.

Upgrade method

Run

Migration Assistant Find the hashbang: false option Example.


##history: true replacementAll routing model options will be reduced to a single

mode option. You need to update:

var router = new VueRouter({
  history: 'true'
})
to this writing:

var router = new VueRouter({
  mode: 'history'
})

Upgrade methodRun

Migration Helper

Find an example of the history: true option.


abstract: true replacementAll routing model options will be reduced to a single

mode option. You need to update:

var router = new VueRouter({
  abstract: 'true'
})
to this writing:

var router = new VueRouter({
  mode: 'abstract'
})

Upgrade methodRun

Migration Helper

Find an example of the abstract: true option.


Routing options: Misc



##saveScrollPosition replacement

It has been replaced to be acceptable A function's

scrollBehavior options, so the scrolling behavior can be fully customized - even for each route. This will open up a lot of new possibilities, but to simply copy the old behavior:

saveScrollPosition: true

you can replace it with:

scrollBehavior: function (to, from, savedPosition) {
  return savedPosition || { x: 0, y: 0 }
}

Upgrade method

Run

Migration Assistant Find an example of the saveScrollPosition: true option.


root Change your name

Renamed to

base in order to maintain consistency with the <base> tag of HTML.

Upgrade methodRun

Migration Assistant

Find an example of the root option.


##transitionOnLoad RemoveDue to the existence of Vue's transition system

appear

transition control, this option will no longer be needed.

Upgrade method

Run Migration Assistant

Find the

transitionOnLoad: true option Example.


##suppressTransitionError Remove

Removed for the purpose of simplifying the hook. If you really need to suppress transition errors, you can use

trycatch instead.

Upgrade method

Run

Migration Assistant Find the suppressTransitionError: true option Example.


Routing hooks



activate Replace

Use

beforeRouteEnter This component is replaced.

Upgrade method

Run

Migration Assistant Find an example of the activate hook.


##canActivate Replace Use

beforeEnter in routing as an alternative.

Upgrade methodRun

Migration Assistant

Find an example of the canActivate hook.


##deactivate#RemoveUse the

beforeDestroy or destroyed hooks instead.

Upgrade methodRun

Migration Assistant

Find an example of deactivate hook.


##canDeactivate Replace Use

beforeRouteLeave

in the component instead.

Upgrade method

Run Migration Assistant

Find an example of the

canDeactivate hook.


canReuse: false remove will no longer be used in the new Vue routing.

Upgrade method

Run Migration Assistant

Find the

canReuse: false option Example.


data replace $route

The properties are reactive, so you can just use a watcher to respond to route changes, like this:

watch: {
  '$route': 'fetchData'
},
methods: {
  fetchData: function () {
    // ...
  }
}

Upgrade method

Run Migration Assistant

Find the example of

data hook.


##$loadingRouteData Remove

Define your own properties (for example:

isLoading), and then update the loading status in the watcher on the route. For example, if you use axios to get data:

data: function () {
  return {
    posts: [],
    isLoading: false,
    fetchError: null
  }
},
watch: {
  '$route': function () {
    var self = this
    self.isLoading = true
    self.fetchData().then(function () {
      self.isLoading = false
    })
  }
},
methods: {
  fetchData: function () {
    var self = this
    return axios.get('/api/posts')
      .then(function (response) {
        self.posts = response.data.posts
      })
      .catch(function (error) {
        self.fetchError = error
      })
  }
}