Vue routing (router) realizes the switching of the navigation bar picture

The navigation bar realizes picture switching, that is, the path of the picture is changed when clicked. If you use the general idea, that is, every time you click, call the method, so that other navigation pictures will change, which is too troublesome. One or two navigations is fine, if multiple navigations are written, the code is too complicated.

Optimization ideas:

1. Write a container and store the
content of each navigation option as an object. The content includes:

  • Picture before and after switching
  • Because the navigation switch is implemented by routing, a path must be added to each attribute of the object. When used to implement v-for traversal, add the to attribute to each <router-link> </router-link> tag
export default {
  data(){
    return{
     //底部导航栏的切换
     navPicArray:[
       {
         icon:require('./图片/首页.png'),
         active:require('./图片/点击首页.png'),
         path:"/commend",
         name:"首页"
       },
       {
        icon:require('./图片/分类.png'),
         active:require('./图片/点击分类.png'),
         path:"/greencat",
         name:"分类"
       },
       {
        icon:require('./图片/购物车.png'),
         active:require('./图片/购物车.png'),
         path:"/buycar",
         name:"首页"
       },
       {
        icon:require('./图片/我的.png'),
         active:require('./图片/点击我的.png'),
         path:"/mine",
         name:"我的"
       },
     ],
     num:0,
    }
  },
  methods:{
    changeImg(index){
      console.log("index改变之前"+index)
     
     this.num=index
     console.log("index改变之后"+index)
  
    }
  }

}

2. Use v-for to traverse the content of each router. A click function is implemented for each router. The effect of clicking is to highlight the navigation picture where the current router is located, and the others are the original pictures. Here we are using index. And create a new attribute variable num=0, when index and num are equal, the picture is highlighted, when not equal, it is the original picture

<div id="app">
    <div id="nav">
      <ul>
        <li 
        v-for="(item,index) in navPicArray"
        :key="index"
        @click="changeImg(index)"
      
        >
      <router-link :to="item.path" >
      <img  alt="" v-bind:src="item.icon" v-show="index!=num">
      <img  alt="" v-bind:src="item.active" v-show="index==num">
      </router-link>

        </li>
      </ul>

    </div>
    <router-view/>
  </div>

Effect picture:

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/104176220