2021-7-7 Vue实现切换图片功能代码

<!DOCTYPE html>
<html>
<head>
    <title>        
    </title>
</head>
<body>
<div id="app">
    <ol>
        <li v-for="(item,key,index) in obj"><input type="button" :value="key" name="" @click="changeImage"></li>
    </ol>
    <div>
        <img :src="imgSrc">
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript"></script>
<script type="text/javascript">
//在原生js中使用
var obj={
    name:'Source/image/r1.jpg',
    name1:'Source/image/r2.jpg',
    name2:'Source/image/r3.jpg'
};

new Vue({
  el: '#app',
  data: {
       obj,
       imgSrc:'Source/image/r1.jpg'
  },
  methods:{
    changeImage:function(event){
    this.imgSrc=this.obj[event.target.value];
    }
  }
})
</script>
</body>
</html>
实例1
<!DOCTYPE html>
<html>
<head>
    <title>        
    </title>
    <style type="text/css">
      .active{
        background-color: blue;
      }
    </style>
</head>
<body>
<div id="app">
    <ol>
        <li v-for="(item,key,index) in obj" v-bind:class="index==imgIndex?'active':''"><input type="button" :value="key" name="" @click="changeImage(index,$event)"></li>
    </ol>
    <div>
        <img :src="imgSrc">
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript"></script>
<script type="text/javascript">
//在原生js中使用
var obj={
    name:'Source/image/1.jpg',
    name1:'Source/image/2.jpg',
    name2:'Source/image/3.jpg'
};

new Vue({
  el: '#app',
  data: {
       imgIndex:0,
       obj,
       imgSrc:'Source/image/1.jpg'
  },
  methods:{
    changeImage:function(index,event){
    this.imgSrc=this.obj[event.target.value];
    this.imgIndex=index;
    }
  }
})
</script>
</body>
</html>
实例2

 

image的src使用相对路径,效果如下图

 

 

 

posted @ 2021-07-07 23:02  月长生  阅读(92)  评论(0)    收藏  举报