Try fresh vue3 0 - start after reading

background

Continue the previous three articles:

Before the formal development, you need to introduce the routing changes, which is even for vue3 0 to have a preliminary understanding and complete the infrastructure of the project.

Installing Vue router

//Current latest version
npm i --save vue-router@4.0.0-beta.9
"vue-router": "^4.0.0-beta.9"
//to configure
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  //Createwebhistory() host mode
  history: createWebHashHistory(),//hash mode 
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    // Dynamic path parameters start with a colon
    { path: '/home', component: () => import('../views/home.vue') },
  ],
})
export default router
//Use main js
app.use(router)

scoped slot

Originally, I wanted to render < router link > into some kind of label, but it will not be intuitive and clear enough to use

//before
//Tag = "button" router link will render as a button label
<router-link to="/" tag="button">
    <Icon>home</Icon><span class="xs-hidden">Home</span>
</router-link>
//Then replace with scoped slot
<router-link to="/">
  <button role="link">
    <Icon>home</Icon><span class="xs-hidden">Home</span>
  </button>
</router-link>
  • Delete event attribute( vue2.0 router Document event introduction)
    The default is' click ', which declares events that can be used to trigger navigation. It can be a string or an array containing strings. Also deleted and replaced with a scope slot.
  • Stop automatically assigning click events to internal anchors
  • Added scoped slot API
  • Add custom prop to completely customize the rendering of router link

  • Abbreviation (PIT)

    //It was introduced from the second part that v-slot has a short form, but it is worth noting that the writing method below is not suitable for browser rendering
    <router-link to="/about" #custom="{ href }">
       <a :href="href">1.{{href}}</a>
     </router-link>
     <router-link to="/about" v-slot:custom="{ href }">
       <a :href="href">2.{{href}}</a>
     </router-link>
    
     <router-link to="/about" custom v-slot="{ href }">
       <a :href="href">3.{{href}}</a>
     </router-link>

After rendering, only the third result is displayed normally

---
###API of Vue router

And vue3 0, all APIs are import ed and not put in this (print require ('vue router '))

meta attribute (attribute that attaches data to the route)

{ path: '/my', meta: { requiresAuth: true }}
//before
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !auth.loggedIn()) next('/login')
  else next()
})
//Recommendation 3.0
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth))
  // ...do sth
})

Router link active / router link exact active class name

  • Aliases and sub routes will also be activated
  • params inconsistency will not be activated

Assume current route / parent/1/child/2

url active exact active
/parent/1/child/2
/parent/1/child/3 X X
/parent/1/ X

Provides an API that can add or delete routing records during routing operation

//my.vue
import {useRouter,useRoute} from 'vue-router' //See the current API of Vue router described above
setup(props,ctx){
   console.log(useRouter(window.location.pathname));//Similar to the original this$ router
   console.log(useRoute(window.location.pathname));//Similar to the original this$ route
 }
//Value of route record
const routeRecord: RouteRecord = {
  path: '/new-route',
  name: 'NewRoute',
  component: NewRoute
}
router.addRoute(route: RouteRecord) //Add a routing record
router.removeRoute(name: string | symbol) //delete
router.hasRoute(name: string | symbol)://Judge whether it exists
router.getRoutes(): RouteRecord[] //Get record list

Route jump

  • Clearly define the route jump failure, and then how to catch the error
  • Route jump will be in Promise form
  • Set router Push and router afterEach,router.onError consistent

    router.push('/dashboard').then((failure) => {
      if (failure) {
        failure instanceof Error // true
        failure.type // NavigationFailure.canceled [aborted,canceled,duplicated]
      }
    }).catch(()=>{...})

Use keep alive and transition at the same time

//before
<transition :name="transitionName" >
  <keep-alive >
    <router-view></router-view>
    <router-view></router-view>
  </keep-alive>
</transition>
//after
<router-view v-slot="{ Component }">
  <transition :name="transitionName" mode="out-in">
    <component :is="Component"></component>
  </transition>
</router-view>

Rolling behavior

Not commonly used, vue2.0 on the official website

//The change is not big, but to be closer to the original, the attribute names are unified
{ selector:..,x: 0, y: 200,behavior }
// becomes
{ el:...,left: 0, top: 200,offset }

When activating a route, add logical judgment and display other contents in the route view (such as some loading status)

<router-view :route="routeWithModal"></router-view>
const App = {
  computed: {
    routeWithModal() {
      if (backgroundView) {
        return this.$router.resolve(backgroundView)
      } else {
        return this.$route
      }
    }
  }
}

The routing guard can return a value or Promise directly without using next

// before
router.beforeEach((to, from, next) => {
  if (!isAuth) next(false)
  else next()
})

// Later can
router.beforeEach(() => isAuth)

last

After understanding the relevant changes of routing after installation, you can start to work directly. The whole process, vue3 The change of 0 is still acceptable and is developing in a better direction. vite is also recommended. Many things are built-in and can be used out of the box. As for typesciprt, it's just vue3 0 better supports ts syntax, but whether it is used or not depends on the project and the developer itself. At present, vue3 With the use of 0, you can actually start writing projects. The Vue Composition API is not introduced, but the simple and common APIs have been used above, and will be updated later.

github code address

Here is the introduction. If there is any omission, you are welcome to add. If you like, collect some praise.

Tags: Javascript node.js Front-end html5 Vue.js

Posted by mjedman1 on Sun, 15 May 2022 12:54:02 +0300