Vue-CLI创建项目

3 篇文章 0 订阅
1 篇文章 0 订阅

一、安装vue-cli

Vue-CLI官网地址

//version 3.x.使用
npm install -g @vue/cli
//(1.x or 2.x) 使用
npm install vue-cli -g

二、创建项目

//version 3.x.使用
vue create app-demo
//(1.x or 2.x) 使用
vue init webpack app-demo  //(项目名称)

创建好之后:运行项目

 npm run dev  

运行结果会出现这样的提示信息:

I  Your application is running here: http://localhost:8080

然后浏览器打开: http://localhost:8080/#/

三、项目说明

1、项目的目录结构

这是vue-cli 的1.x和2.x版本创建的项目目录,3.x版本创建的项目目录有些地方不太一样。
目录结构

  • build: 项目构建(webpack)相关代码
  • config:配置目录,包括端口号等。我们初学可以使用默认的。
  • node_modules npm :加载的项目依赖模块
  • src :这里是我们要开发的目录,基本上要做的事情都在这个目录里。里面包含了几个目录及文件:
  • assets: 放置一些图片,如logo等。
  • components: 目录里面放了一个组件文件,可以不用。
  • App.vue: 项目入口文件,我们也可以直接将组件写这里,而不使用
  • components 目录。
  • main.js: 项目的核心文件。
  • static 静态资源目录,如图片、字体等。
  • test 初始测试目录,可删除
  • .xxxx文件 这些是一些配置文件,包括语法配置,git配置等。
  • index.html 首页入口文件,你可以添加一些 meta 信息或统计代码啥的。
  • package.json 项目配置文件。
  • README.md 项目的说明文档,markdown 格式

2、开发环境配置

config目录下的index文件中

 dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    //配置路径路径的跳转,访问static目录下的静态资源
    proxyTable: {
      '/api': {
        target: 'http://localhost:8080',
        pathRewrite: {
          '^/api': '/static/mock'
        }
      },
    } ,
    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    //(端口号可以自己设置)
    port: 8080, 
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    /**
     * Source Maps
     */
    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',
    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,
    cssSourceMap: true
  },

四、Vue组件

1、创建Vue组件

在项目中的components文件夹下,如果使用WebStorm 编辑器,创建一个vue的文件,WebStorm就会自动把如下内容加进去。

<template>
  //这里需要一个div
</template>
<script>
export default {
  name: 'Home'
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

注意:在vue-cli创建的项目中,任何一个组件都包含:template(视图)script(js代码)和style(样式这三部分)

2、组件引用

在一个组件中如果要引用其他组件。

  1. 引入组件,比如Swiper组件。
  2. 声明组件。即添加在components属性对象里面
import Swiper from './Swiper'  //1引入组件
export default {
  name: 'Home',
  components: {Swiper},//2声明组件
  ····
}
  1. 使用组件。
<template>
  <div class="main">
    <Swiper/>//使用Swiper组件
  </div>
</template>

五、组件传值

1、 父组件传值子组件

父组件给子组件传值,通过给子组件添加属性,然后子组件通过props获取。

<template>
    <div class="parent">
      <div>This is  the components of parents .</div>
      <input type="text" v-model="id"/>
      <div>v-model数据单向绑定: <span>{{id}}</span></div>
      <button @click="changeId">修改数据</button>
      <!--父组件给子组件传值,v-bind把传递的数据变成活数据-->
      <Son :sonId="id" :name="name" :num="number"/>
    </div>
</template>
<script>
import Son from './Son'//引入子组件
export default {
  name: 'Parent',
  components: {Son},
  data () {
    return {
      id: '',
      name: '小明',
      number: 1
    }
  },
  methods: {
    changeId (even) {
      this.id = '这是修改之后的数据!!!'
    }
  }
}
</script>
<style scoped>
   span{
     font-size: 20px;
     color:blue;
   }
</style>

子组件son.js

<template>
  <div class="son">
      This is the components of son .
    <div class="span">
    接收父组件传递的值:{{sonId}}====={{name}}====={{num}}</div>
  </div>
</template>
<script>
export default {
  name: 'Son',
  // 子组件接受数据
  // props: ['sonId', 'name'],
  props: {
    sonId: String,
    name: String,
    // 默认值如果是Object或者Array类型,就要用函数
    num: {type: Number, required: true, default: 10}
  },
  data () {
    return {
    }
  }
}
</script>
<style scoped>
.span{
  font-size: 20px;
  color: #F0F;
}
</style>

运行结果:父组件传值子组件

2、子组件传值父组件

子组件给父组件传值,通过自定义事件发送数据给父组件,父组件通过事件接收子组件传过来的值。

//父组件
<template>
  <div class="parentCom">
    <Child @sendMsg="getMsg" :num="getNum"/>
    <input type="text" v-model="num"/>
    <br/>
    <span>父组件接收子组件发送过来的数据:{{info}}</span>
  </div>
</template>
<script>
import Child from './Child'
export default {
  name: 'ParentComponent',
  components: {Child},
  data: function () {
    return {
      info: '',
      num: ''
    }
  },
  computed: {
    getNum () {
      return this.num - 0
    }
  },
  methods: {
    getMsg (data) {
      console.log(data)
      this.info = data
    }
  }
}
</script>
<style scoped>
 span{
   font-size: 30px;
   oolor:#F00FF0;
 }
</style>

子组件

<template>
  <div class="childCom">
      <span>子组件发送数据:</span>
      <br/>
      <strong>{{msg}}</strong>
      <br/>
      <!--子组件发送数据通过自定义事件-->
      <button @click="sendMsg">发送数据</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    num: {type: Number, default: 10}
  },
  data () {
    return {
      msg: '我是子组件的值。'
    }
  },
  computed: {
    addNum () {
      return this.num * 5
    }
  },
  methods: {
    sendMsg: function () {
       //给sendMsg时间添加数据
      this.$emit('sendMsg', this.addNum);
      // this.$emit('sendMsg', this.msg)
    }
  }
}
</script>
<style scoped>
span{
  color:#666666;
  font-size: 18px;
}
</style>

运行效果:子组件传值父组件

3、同级组件传值

同级组件之间传值,也是通过事件进行。用vue. e m i t ( " 事 件 名 " , " 事 件 参 数 " ) ; 发 送 数 据 , 用 v u e . emit("事件名","事件参数");发送数据,用vue. emit("","");vue.on(“事件名”,“回调函数”);接收参数。

3.1、首先创建一个vue实例

eventBus中我们只创建了一个新的Vue实例,以后它就承担起了组件之间通信的桥梁了,也就是中央事件总线。

//eventBus
import Vue from 'Vue'
export default new Vue()
3.2、创建同级组件

firstChild.vue

<template>
    <div id="firstChild">
       <h3>This is the first child.</h3>
      <button @click ='sendMsg'>向兄弟组件传值</button>
    </div>
</template>
<script>
import bus from '../../assets/eventBus'
export default {
  name: 'FirstChild',
  data () {
    return {
    }
  },
  methods: {
    sendMsg: function () {
      console.log(self)
      bus.$emit('userDefinedEvent', "This is the Brother's  data .")
    }
  }
}
</script>
<style scoped>
</style>

secondChild.vue

<template>
    <div id="secondChild">
        <h3>This is the secondChild component .</h3>
        <p>从同级组件firstChild接收到的数据:{{msg}}</p>
    </div>
</template>

<script>
import bus from '../../assets/eventBus'
export default {
  name: 'secondChild',
  data () {
    return {
      msg: ''
    }
  },
  mounted: function () {
    var self = this
    bus.$on('userDefinedEvent', function (msg) {
      self.msg = msg
    })
  }
}
</script>

<style scoped>
</style>

运行效果

六、Vue数据请求

Axiosnpm提供的供vue组件请求数据的工具

1、Axios请求数据

axios的官网地址:axios

  1. 下载axios
   npm install axios
  1. 引入axios。在组件script标签底下引入
  import axios from 'axios'
  1. 请求数据
methods: {
    getRecommondList () {
      var _this = this
      axios.get('/static/mock/index.json')
        .then(function (resp) {
          resp = resp.data
          console.log('打印推荐列表')
          console.log(resp.data.recommendList)
          _this.recommondList = resp.data.recommendList
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }

七、Vue的轮播

swiper可以做专业的轮播图。

1、swiper轮播

打开Swiper官网,查看轮播图的制作流程。

  1. 下载swiper。
   npm install swiper
  1. vue中使用swiper。
<template>
   <div class="swiper-container" @mouseover="stop" @mouseout="start">
    <div class="swiper-wrapper">
      <div class="swiper-slide"><img src="../assets/1.jpg" alt=""></div>
      <div class="swiper-slide"><img src="../assets/2.jpg" alt=""></div>
      <div class="swiper-slide"><img src="../assets/3.jpg" alt=""></div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>
    <!-- 如果需要导航按钮 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
    <!-- 如果需要滚动条 -->
    <!-- <div class="swiper-scrollbar"></div> -->
  </div>
</template>
<script>
import "swiper/dist/css/swiper.min.css"; //组件内引入CSS
import Swiper from "swiper"; //组件内引入js
export default {
  name: "Swiper",
    mounted() {          //生命周期钩子 mounted阶段把mySwiper函数挂载上去 created开始阶段不行
    this.mySwiper;
    },
  computed: {
    mySwiper() {
      return new Swiper(".swiper-container", {
        //实例化swiper
        loop: true, //循环播放
        mousewheel: true, //鼠标滚轮播放
        autoplay: {
          delay: 1000,
          stopOnLastSlide: false, //切换最后一张停止默认true停止   false继续
          disableOnInteraction: false //用户操作之后是否停止自动播放 默认停止true, false就是操作之后还会自动播放
        },
        pagination: {
          //分页器
          el: ".swiper-pagination",
          clickable: true
        },
        navigation: {
          //前进后退按钮
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev"
        }
      });
    }
  },
  methods: {
    /* 鼠标进入mouseover停止轮播 */
    stop() {
      // console.log(this.mySwiper);
      this.mySwiper.autoplay.stop();
    },
    /* 鼠标离开mouseout开启轮播 */
    start() {
      this.mySwiper.autoplay.start();
    }
  }
};
</script>
<style scoped>
.swiper-container {
  width: 600px;
  height: 600px;
}
</style>

八、Vue的路由

vue-router来做路由导航。帮助前端页面实现跳转。

1、 安装vue-router。

    npm install vue-router

2、 引入vue-router。

	import Vue from 'vue'
	import VueRouter from 'vue-router'
	Vue.use(VueRouter)

3、路由路径配置

router目录下的index.js文件中配置路由地址

export default new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: Home
    },
    {
      path: '/home',
      name: 'Header',
      component: Header
    }
  ]
})
  1. 在入口文件的主组件App.vue中使用router
	<template>
	  <div id="app">
	    <router-view/>
	  </div>
	</template>

项目运行之后就可以使用:http://localhost:8080/#/ 或者 http://localhost:8080/#/home 实现页面的跳转。

4、点击切换页面

<router-link>实现页面的点击跳转,渲染之后将会以<a>的形式出现在页面上。

 <router-link to="/home" slot="left">
    <mt-button icon="back">返回</mt-button>
 </router-link>

点击上面跳转,路径会直接到home页面。

九、ElementUI使用

点击Element-UI官网地址进入查看详情。Element-UI是一个专业的vue和React的组件库,使用非常简单。Element-UI主要针对PC端使用的组件库。

1、装组件库

npm i element-ui -S
//或者引入文件
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

2 引入组件库

在vue的main.js文件中

2.1完全引入

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);
new Vue({
  el: '#app',
  render: h => h(App)
});

2.2按需引入

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);

3使用组件库

在页面需要的地方把示例代码贴进去,运行查看效果。例如:

<template>
   <el-container>
     <el-header>头部标签</el-header>
     <el-container>
       <el-aside width="200px">Aside</el-aside>
       <el-container>
         <el-main>
           <el-row>
             <el-button icon="el-icon-search">默认按钮</el-button>
             <el-button type="primary" class="el-icon-edit">主要按钮</el-button>
             <el-button type="success">成功按钮</el-button>
             <el-button type="info">信息按钮</el-button>
             <el-button type="warning">警告按钮</el-button>
             <el-button type="danger">危险按钮</el-button>
           </el-row>
         </el-main>
         <el-footer>Footer</el-footer>
       </el-container>
     </el-container>
   </el-container>
</template>
<script>
export default {
 name: 'Home'
}
</script>
<style scoped>
 .el-header{
   position: fixed;
   top: 0;
   width: 100%;
 }
 .el-header, .el-footer {
   background-color: #B3C0D1;
   color: #333;
   text-align: center;
   line-height: 60px;
 }
 .el-aside {
   background-color: #D3DCE6;
   color: #333;
   text-align: center;
   line-height: 200px;
 }
 .el-main {
   background-color: #E9EEF3;
   color: #333;
   text-align: center;
   line-height: 160px;
 }
 body > .el-container {
   margin-bottom: 40px;
 }
 .el-container:nth-child(5) .el-aside,
 .el-container:nth-child(6) .el-aside {
   line-height: 260px;
 }
 .el-container:nth-child(7) .el-aside {
   line-height: 320px;
 }
</style>

运行效果:element-ui使用

十、MintUI使用

点击mint-ui官网进入查看。Mint-UI和element不同,针对移动端。

1、安装Mint-Ui

npm install --save mint-ui

2、 引入组件

可以全部引入也可以按需引入,同样也实在main.js文件中。

import Vue from 'vue'
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import App from './App.vue'

Vue.use(MintUI)

new Vue({
  el: '#app',
  components: { App }
})

3、 使用组件

在页面中需要的地方,赋值粘贴示例代码。

<!--头部组件-->
<mt-header fixed title="主页面">
  <router-link to="/home" slot="left">
    <mt-button icon="back">返回</mt-button>
  </router-link>
  <mt-button icon="more" slot="right"></mt-button>
</mt-header>
<!--加载刷新动画-->
<!--<Indicator/>-->
<mt-swipe :auto="4000" :show-indicators="true" @change="handleChange">
  <mt-swipe-item>1</mt-swipe-item>
  <mt-swipe-item>2</mt-swipe-item>
  <mt-swipe-item>3</mt-swipe-item>
  <mt-swipe-item>4</mt-swipe-item>
</mt-swipe>

上面的实现效果:mint-ui使用

十一、单页面和多页面应用

1、单页面(Single-page Application)

页面之间切换不会请求多个页面,js会感知页面变化,页面发生变化js会动态的清除当前页面内容,把新的页面内容加载进来。

1.1、优点

页面之间切换快。

1.2、缺点

  1. 首屏展示时间稍微缓慢一点。
  2. 搜索引擎优化效果会差一点。因为搜索引擎只识别html页面的内容不识别js当中的内容,这样单页面在百度和谷歌的搜索优化排名会有影响。
    解决方案:vue提供了服务器端渲染技术,完美的解决了这个问题。

2、多页面

需要页面之间进行跳转,会多次请求不同的页面。

2.1、优点

  1. 首屏时间快。
  2. SEO效果好。

2.2、缺点

页面切换慢。主要是页面切换要重新请求然后渲染。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值