webpack+Vue实现轮播图

2,211 阅读3分钟

前言

本来如果只是想做个轮播图的话不太需要这么麻烦的构建webpack项目,但是我的目的不是只做个轮播图这么简单,主要是想用webpack搭建一个vue项目,然后在里面实现了一个轮播图组件。在这个框架的基础上还可以实现很多其他的功能,大家可以下载源码自己往里面加东西。这里我提供本项目的github地址,希望大家批评指正!!!



通过webpack构建vue项目

通过webpack构建vue项目和构建普通项目基本套路都一样,只是需要多添加一个vue-loader的插件来加载并编译.vue文件

这里先放上我的文件目录


dist文件夹放的是编译之后的文件

node_modules是项目依赖

index.html是项目的首页,编译完之后,在dist文件下也会有一个index.html文件

src是代码主要的文件夹(里面的main.js文件是项目的入口文件,它会被编译成dist文件夹下面的demo.js文件),我们主要的编码工作就是在这个文件夹下面进行的,可以根据自己的需求,在这个文件夹下面分一些子文件夹。

package.json文件保存的项目的版本信息,依赖信息等

webpack.config.js是项目的配置文件,规定了文件加载方式,入口出口地址等(entry,output,loader,plugin等)

主要搭建步骤:

1、引入webpack

npm install webpack --save-dev

2、引入vue

npm install vue --save

3、引入babel

npm install --save-dev babel-core babel-loader

4、引入加载器(css、file、font等等)

npm install --save-dev css-loader style-loader

npm install --save-dev css-loader style-loader

注意:引入之后需要在webpack.config.js文件里面配置文件的加载方式

module: {
        rules: [
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                use: ['file-loader']
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                use: ['url-loader'],
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000
                }
            }
        ]
    }

5、引入vue-loader

npm install --save-dev vue-loader vue-template-compiler

在webpack.config.js文件里面配置

{
   test: /\.vue$/,
   loader: 'vue-loader'
 }

6、引入HtmlWebpackPlugin 插件

npm install --save-dev html-webpack-plugin

webpack.config.js文件里面配置

plugins:[
     new HtmlWebpackPlugin({
          title: 'vue demo',
          template: 'index.html'         
     })
]

7、配置webpack-dev-server

在我们实际开发中需要将代码部署在server中,而不是在浏览器中直接打开文件。此时我们需要使用webpack的 webpack-dev-server。

npm install --save-dev webpack-dev-server 

在webpack.config.js 文件中需要指定一个文件夹,告诉开发服务器需要从哪儿加载文件

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "demo.js"
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'vue demo',
            template: 'index.html'
        })
    ],
    devServer:{
        contentBase:"./dist"
    },
    module: {
        rules: [{
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/
            }, {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }, {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000
                }
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
        }
    }
}

在package.json中添加一个script脚本

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"webpack-dev-server --open",
    "build": "webpack"
  }

然后输入如下命令

npm run dev 

启动完成浏览器会自动打开页面

8、热部署

new webpack.HotModuleReplacementPlugin()

然后去package.json中,script 里面dev的值中加上 --hot -only

"dev": "webpack-dev-server --hot-only --open" 

以上就是搭建webpack的过程,如果需要详细了解请参考这篇文章,或者直接看我的项目

轮播图

这里就分为三部分来讲

App.vue

先写好布局

<template>
    <div class="container" @mouseenter="stop" @mouseleave="go">
        <ul class="wrap"  :style="containerStyle">
            <li v-for="(item,index) in sliders" :key="index">
                <img class="img" :src="item.img" alt="">
            </li>
        </ul>
        <ul class="dot">
            <li v-for="(index) in sliders.length" :class="{'active':index===currentIndex+1}" @mouseover="change(index)">{{index}}</li>
        </ul>
    </div>
</template>

这里是.vue文件,需要在main.js里面import进去

import Vue from 'vue'
import './style/main.css'
import App from './App.vue'
new Vue({
    el: '#app',
    template: '<App/>',
    components: { App }
})

接下来是相关的逻辑代码,也是写在App.vue里面的

<script>
    export default {
        name: 'slider',
        data () {
            return {
                sliders:[
                    {
                        img:'./images/1.jpg'
                    },
                    {
                        img:'./images/2.jpg'
                    },
                    {
                        img:'./images/3.jpg'
                    },
                    {
                        img:'./images/4.jpg'
                    },
                    {
                        img:'./images/5.jpg'
                    }
                ],
                currentIndex:0,
                timer:null,
                initialInterval:5
            }
        },
        computed:{
            containerStyle(){  //这里用了计算属性,用transform来移动整个图片列表
                return {
                    transform:`translate3d(${this.currentIndex*-600}px, 0, 0)`
                }
            },
        },
        created() {
            //在DOM加载完成后,下个tick中开始轮播
            this.$nextTick(() => {
                this.timer = setInterval(() => {
                    this.play()
                }, 2000)
            })
        },
        methods:{
            play(){
                this.currentIndex++;
                if (this.currentIndex > this.sliders.length - 1) {
                    this.currentIndex = 0
                }
                //console.log(this.currentIndex);
            },
            go(){
                this.timer = setInterval(() => {
                    this.play()
                }, 2000)
            },
            stop() {
                clearInterval(this.timer)
                this.timer = null
            },
            change(dotIndex){
                console.log(dotIndex);
                this.currentIndex=dotIndex-1;
            }
        }
    }
</script>

css代码

* {
    margin:0;
    padding:0;
}
.container {
    position: absolute;
    width: 600px;
    height: 400px;
    top:0;
    bottom:0;
    right:0;
    left:0;
    margin:auto;
    box-shadow: 0 0 5px green;
    overflow: hidden;
}
.wrap {
    position: absolute;
    width: 3000px;
    height: 400px;
}
.container .wrap li {
    float: left;
    width: 600px;
    height: 400px;
    list-style-type:none ;
}
.container .wrap .img {
    float: left;
    width: 600px;
    height: 400px;
    object-fit: cover;
}
.container .dot {
    position: absolute;
    right: 150px;
    bottom:20px;
    width: 200px;
    height: 10px;
    z-index: 2;
}
.container .dot li{
    margin-left: 5px;
    display: inline-block;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: gray;
    text-align: center;
    color:white;
    cursor: pointer;
    font-size:5px;
}
.container .dot .active{
    background-color: green;
}

index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue demo</title>
</head>
<body>
<div id="app">
</div>
</body>
</html>

然后轮播图就完成啦