Vue-CLI创建项目 - Go语言中文社区

Vue-CLI创建项目


安装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/#/

项目说明

项目的目录结构

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

开发环境配置

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

创建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(样式这三部分)

组件引用

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

  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>

组件传值

父组件传值子组件

父组件给子组件传值,通过给子组件添加属性,然后子组件通过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>

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

子组件传值父组件

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

//父组件
<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>

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

同级组件传值

同级组件之间传值,也是通过事件进行。用vue.emit(&quot;&quot;,&quot;&quot;);vue.emit(&quot;事件名&quot;,&quot;事件参数&quot;);发送数据,用vue.

1 首先创建一个vue实例

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

//eventBus
import Vue from 'Vue'
export default new Vue()

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组件请求数据的工具

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可以做专业的轮播图。

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.

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/WeiAiGeWangFeiYuQing/article/details/83415824
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢