Article From:https://www.cnblogs.com/shaoshuai0305/p/9549389.html

Routing, in fact, means pointing. When I click the home button on the page, the content of home is displayed on the page. If I click the about button on the page, the content of about is displayed on the page. Home button => home content,The about button = & gt; about content, or a mapping, so there are two parts on the page, one is the click part, the other is the part that displays the content after clicking.  

  After clicking, how to do the right correspondence, for example, I click the home button, how the page just shows the content of home. This is to configure routing in the JS file.

  There are three basic concepts in routing: route, routes, router.

    1, route,It’s a route, as you can see from this English word, it’s singular, Home button = & gt; home content, this is a route, about button = & gt; about content, this is another route.

    2, routes It is a group of routes that combine each route above to form an array. [{home button => home content}, {about button => about content}]

    3, router It is a mechanism, which is equivalent to a manager who manages routing. Because routes only define a set of routes, where does it sit still, and what happens when the request actually comes? What happens when a user clicks the home button? At this point, router worked.It goes to routes to find the corresponding home content, so the home content is displayed on the page.

    4,The routing in the client is actually the display and hiding of the DOM element. When home content is displayed on the page, all contents in about are hidden, and vice versa. There are two ways to implement client Routing: Based on hash and HTML5 histor.Y api.

  vue-routerThe routing is also based on the above content.

  It is relatively simple to implement routing in Vue. Because everything on our page is componentized, we just need to map the path to the component, and then render the component in the page.

  1, Page implementation (HTML template)

    In vue-router, we see that it defines two tags & lt; router-link & gt; and & lt; router-view & gt; to correspond to the click and display parts. < router-link> that is to say.The clickable part of the page, & lt; router-view & gt; defines the display part, which is where the content of the partition is displayed after clicking. So < router-link> there is another very important attribute, to, which is defined after clicking.Where to go, such as: < router-link to= “/home” > Home< /router-link>

  2, js Configure routing in

    First, define route, a routing implementation. It is an object consisting of two parts: path and component. path refer to the path, and component refers to the component. Such as: {path: ‘/home’, compOnent: home}

    We have two routes to form a routes:.

const routes = [
  { path: '/home', component: Home },
  { path: '/about', component: About }
]

  Finally, a router is created to manage the route, which is created by the constructor, new vueRouter (), accepting the routes parameter.

const router = new VueRouter({
      routes // routes: routes Abbreviations})

  After the configuration is completed, the router instance is injected into the Vue root instance, and the routing can be used.

const app = new Vue({
  router
}).$mount('#app')

  Execution: When the user clicks the router-link tag, he looks for its to attribute, its to attribute, and the path {path: home’, component: Home} path configured in JSOne-to-one correspondence, which finds the matching component, and finally renders the component to & lt; router-view & gt; where the tag is located. All of these implementations are based on hash.

 vue-cli Create a project experience. Of course, don’t forget to install vue-router.

  1, In the SRC directory, create two components, home.vue and about.vue.

Copy code ></span></div><pre><template>
    <div>
        <h1>home</h1>
        <p>{{msg}}</p>
    </div>
</template>
<script>
    export default {
        data () {
            return {
                msg:
Copy code ></span></div></div><div class=
Copy code ></span></div><pre><template>
    <div>
        <h1>about</h1>
        <p>{{aboutMsg}}</p>
    </div>
</template>
<script>
    export default {
        data () {
            return {
                aboutMsg: 'I am the about component.}}}< /script></pre><div class=Copy code ></span></div></div><p>  2, Define < router-link > and < /router-view&gt in App.vue;</p><div class=
Copy code ></span></div><pre><template>
  <div id=
Copy code ></span></div></div><p>  3,  In the SRC directory, a new router.js definition router is defined, which is to define the mapping from path to component.</p><div class=
Copy code ></span></div><pre>import Vue from
Copy code ></span></div></div><p>  4, Injecting the route into the root instance to start the routing. There is also a way to inject vuex store directly into the root instance, just as vuex store injects into the root instance. Route is introduced into main.js and injected into the root instance.</p><div class=
Copy code ></span></div><pre>import Vue from 'vue'
import App from './App.vue'

// Introducing routingThe import router from
Copy code ></span></div></div><p>  5, Click home and about on the page to see the components switch back and forth. But there is one problem. When it first entered the page, the page did not show anything. This is because when we first entered the page, its path was’/’, and we didn’t match that path accordingly.Set. Generally, the home page is displayed as soon as the page is loaded, and we also point this path to the home component. But if we write {path:’/’, component: Home}, Vue will report an error because the two paths point to the same partyTo. What about this? This requires redirection, so-called redirection, is to re-assign it a direction, it is originally access / path, we re-point to’/ home’, it is equivalent to access’/ home’, accordingly, the home component will be displayed on the page. VueRedirect is used to define redirection in Router.</p><div class=
Copy code ></span></div><pre>const routes = [
    {
        path:
Copy code ></span></div></div><p>  Now that the page is normal, home is displayed for the first time and the switch of content can also be seen by clicking.</p><p>6, Finally, let’s see how routing is implemented.</p><p>  When you open the browser console, you first see that the router-link tag renders the a tag, and the to attribute becomes the href attribute of the a tag. Then you see what click jump means. Router-view tags render into components that we define.It’s actually a placeholder, where it is and where the component that matches the path is, so the router-link and router-view tags are paired up.</p><p><img src=

  You can also see that when you click Home and Abot to switch back and forth, the a tag has a style class. Router-link-activity is also switched back and forth, which is vueRouter when router-link is selected.This class is automatically added, so we can also use this class to change the state when it is selected, such as turning it red when it is selected. But when you set. router-link-active {color: red;}, it doesn’t work, and you need to add one before the classA, a.router-link-active {color: red;}, there is no problem. Router-link is not selected, and we want to change the style for it, too. What about adding a class directly to it?Yes, < router-link class= “red” > Home< /router-link>

Dynamic routing

  The routing we defined above is strictly matched, and only if the to attribute in router-link is exactly the same as the path in a route route route in JS can the corresponding component be displayed. But sometimes the reality is not the case when weWhen you visit the website and login successfully, it will show you and your name. Different users login only to show that your name is different, and the rest is the same. This means that it is a component, assuming that it is a user component. Different users (different users’ ID)It will navigate to the same user component. So when we configure the routing, we can’t write dead, that is, the path attribute in the routing, can’t write dead, then how to set? Navigate to user component, there must be different user, ID in the path, then give the wayA dynamic part matches different ids. In vue-router, the dynamic part begins with: / user /: id, and the path becomes / user /: ID.Onent: user.

  Let’s define a user component (just write one yourself), add two router-links to the page for navigation, and finally add a routing configuration to router. JS to experience it

  app.vue Add two router-link:

Copy code ></span></div><pre><template>
  <div id=
Copy code ></span></div></div><p>router.js Configuring user dynamic routing:</p><div class=
Copy code ></span></div><pre>const routes = [
    {
        path:
Copy code ></span></div></div><p>  userassembly</p><div class=
Copy code ></span></div><pre><template>
    <div>
        <h1>User</h1>
        <div>I am user component < /div>< /div>< /template>< script>Export default {}≪ /script></pre><div class=Copy code ></span></div></div><p>  When you click on user123 and user456 on the page, you can see that they both navigate to the user component, configured correctly.    </p><p>  How do we get the dynamic part in dynamic routing? Because in the component you can display different parts, that is, the “your name” mentioned above. In fact, when the entire vue-route is injected into the root instance, within the component, it can be obtained by this. $routeTo the router instance. It has a params attribute to get this dynamic part. It’s an object, the attribute name, the dynamic part ID defined in the path, and the attribute value is the dynamic part of the to attribute in router-link, such as 123. When you use vuex, you want to get the state in the state in the component, using the computed attribute, and here again, in the component, you define a computed attribute<strong>dynamicSegment,</strong> user The components are modified as follows:</p><div class=
Copy code ></span></div><pre><template>
    <div>
        <h1>User</h1>
        <div>I am a user component, and the dynamic part is {{dynamicSegment}}< /div>< /div>< /template>< script>Export default {Computed: {DynamicSegment () {Return this.$roUte.params.id}}}< /script></pre><div class=Copy code ></span></div></div><p>  The last problem here is that when dynamic routing switches back and forth, since they all point to the same component, Vue does not destroy and recreate the component, but reuses it, rendering the corresponding component at the first click (e.g. user 123), butWhen user123, user456 clicks and switches back and forth, the component doesn’t change, and the lifecycle of the component doesn’t work. If you want to do something while switching components back and forth, you can only use watch inside the component (user. vue)To monitor $route changes. The above code is monitored by $route.</p><div class=
Copy code ></span></div><pre><script>
    export default {
        data () {
            return {
                dynamicSegment: ''
            }
        },
        watch: {
            $route (to,from){
                // toIt represents the component you are going to, from represents which component you are coming from, they are two objects that you can print out, and they also have a param attributeConsole.log (to);Console.log (from);This.dynamicSegment = to.params.id}}}< /script></pre><div class=Copy code ></span></div></div><p><strong>Nested Route</strong></p><p><strong> </strong> Nested routing is mainly determined by our page structure. When we go to the home page, there are also categories under it, such as mobile phone series, tablet series, computer series. When we click on each category, it still needs to be routed to each section, such as clicking on the phone, and it must correspond toPart of the mobile phone.</p><p align=  In the design of routing, you first go to home, then you go to phone, tablet, computer. Phone, tablet, computer, which is equivalent to the child elements of home. So VueThe childrens attribute is provided. It is also a set of routing, which is equivalent to the routes we wrote.

  First, define three router-link tags on the home page for navigation, and then define a router-view tag for rendering the corresponding components. Router-link and router-view tags should be one to one. HoThe me.vue component is modified as follows:

Copy code ></span></div><pre><template>
    <div>
        <h1>home</h1><br><!-- router-link Note that the route first enters the home, and then enters the corresponding subrouting such as the phone, so write with home - & gt;< p>< RouTer-link to=
Copy code ></span></div></div><p>router.js The configuration route is modified as follows:</p><div class=
Copy code ></span></div><pre>const routes = [
    {
        path:     // The following property is also a lot, because we first enter the home page before we can enter the sub routing.Component: home,
     // SubrouteChildren: [{Path: "phone",Component: phonE},{Path: "tablet",Component: tablet},{Path: "computer",Component: computer}]},{Path: "/about",Component: about},{Path: "/user/: Id",Component: user},{Path: '/',Redirect:'/hOme'}]
Copy code ></span></div></div><p>  When we click on home, words like cell phones appear below it, but no corresponding components are displayed, which is usually not what we want. If you want to click the home to render the corresponding sub components, you need to configure a route. When it enters home, it is in Chi.The corresponding routing path in ldren is empty. The complete Childrens is as follows:</p><div class=
Copy code ></span></div><pre>children: [
    {
        path: // When entering home, the following components are displayed.{Path: "",Component: phone}]
Copy code ></span></div></div><p><strong>Naming routing</strong></p><p><strong>  </strong>Named routing is very simple, because you can tell by name that the route has a name, then you can add a name attribute to the route directly. Add a name attribute to user Routing:</p><div class=
{
        path: "/user/:id",
        name: "user",
        component: user
}

  In the case of named routing, the to attribute can be used in router-link.

 <router-link to="/user/123">User123</router-link> // Equivalent to the following
 <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>   // When using an object as a route, a colon should be added to the to to indicate the binding.

  Programmed navigation: This is mainly applied to button clicks. When you click the button, you jump to another component, which can only use code to call the rourter. push () method. When router is injected into the root instance, the this.$route is passed through the component.R can get router, so it is used in components.

this.$router.push(“home”), You can jump to the home interface.

Link of this Article: Vue-router basic use

Leave a Reply

Your email address will not be published. Required fields are marked *