ant-design-vue Refresh the page navigation bar to automatically locate the homepage problem

 Problem : Vue-router is used in the vue project, page refresh, browser forward and backward will cause the navigation menu homepage to be highlighted

Click Help in the navigation bar, Help is highlighted, and after refreshing the page, Home is highlighted. Every time the browser moves forward and backward, the navigation bar will also be automatically positioned to the homepage.

 Problematic code:

<a-menu 
    theme="light"
    mode="horizontal"
    :defaultSelectedKeys="['1']"
>
    <a-menu-item key="1"><router-link to="/">Home</router-link></a-menu-item>
    <a-menu-item key="2"><router-link to="/search">Search</router-link></a-menu-item>
    <a-menu-item key="3"><router-link to="/help">Help</router-link></a-menu-item>
    <a-menu-item key="4"><router-link to="/contact">Contact</router-link></a-menu-item>
</a-menu>

 Solution: 

Check the ant-design-vue document about the API of the menu navigation menu

Pay attention to the two properties of the Menu component: selectedKeys, defaultSelectedKeys
selectedKeys: the currently selected menu item key array
defaultSelectedKeys: the initially selected menu item key array.
These two properties are used at the same time. If they are used at the same time, they are defaultSelectedKeysinvalid selectedKeys.

If you just want to specify an initial selected menu item, please use it defaultSelectedKeys;
if you need to change the selected item of the Menu component by passing in different props each time, please use it selectedKeys.

So, I used selectedKeys传入this.$route.path property to solve the problem.

Final code:


<a-menu
    theme="light"
    mode="horizontal"
    :selectedKeys="[this.$route.path]"
>
    <a-menu-item key="/"><router-link to="/">Home</router-link></a-menu-item>
    <a-menu-item key="/search"><router-link to="/search">Search</router-link></a-menu-item>item>
    <a-menu-item key="/help"><router-link to="/help">Help</router-link></a-menu-item>
    <a-menu-item key="/contact"><router-link to="/contact">Contact</router-link></a-menu-item>
</a-menu>

 

Guess you like

Origin blog.csdn.net/weixin_42467709/article/details/95484240