vue路由(router)实现导航栏图片的切换

导航栏实现图片切换,即点击时改变图片的路径,如果用一般的思路,即每次点击,调用方法,让其他的导航的图片发生改变,太过麻烦。一两个导航还好,假如多个导航则写出的代码过于繁杂。

优化思路:

1、写一个容器,将每个导航选项的内容作为对象储存
内容包括:

  • 切换前后的图片
  • 因为导航的切换使用路由实现的,所以要为对象的每一个属性添加一个path。用来实现v-for遍历时,为每一个 < router-link> < /router-link>标签添加 to属性
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、用v-for将每一个router的内容遍历出来。为每一个router实现一个点击功能,点击的效果是当前的router所在导航的图片高亮,其他的为原始图片。此处我们使用的是index。并新建一个属性变量num=0,当index和num相等时,实现图片高亮,不相等时,为原始图片

<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>

效果图片:

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhang19903848257/article/details/104176220