sxx的技术专栏 Nodejs and Javascript Coder

vue脚手架项目创建

2018-07-23

阅读:

vue

1. vue脚手架

用来创建vue项目的工具包
创建项目:
    npm install -g vue-cli
    vue init webpack VueDemo
开发环境运行:
    cd VueDemo
    npm install
    npm run dev
生产环境打包发布
    npm run build
    npm install -g serve
    serve dist
    http://localhost:5000

*注意.打包前需配置,才能打开网页

配置打包

解决跨域

在config/index文件中dev:{

    +proxyTable: {//配置代理,解决跨域问题
          '/api': { // 匹配所有以 '/api'开头的请求路径
            target: 'http://localhost:4000', // 代理目标的基础路径
            changeOrigin: true, // 支持跨域
            pathRewrite: {// 重写路径: 去掉路径中开头的'/api'
              '^/api': ''
            }
          }
    +    }
}

重启运行即可解决

2. eslint

用来做项目编码规范检查的工具
基本原理: 定义了很多规则, 检查项目的代码一旦发现违背了某个规则就输出相应的提示信息
有相应的配置, 可定制检查

3. 组件化编程

vue文件包含3个部分
        <template>
          <div></div>
        </template>
        <script>
            export default {
			  props: []/{}
              data(){},
			  computed: {}
              methods: {},
			  
			  watch: {}
			  filters: {}
			  directives: {}
			  components: {}
            }
        </script>
        <style>
        </style>
组件化编码的基本流程
	1). 拆分界面, 抽取组件
	2). 编写静态组件
	3). 编写动态组件
    	初始化数据, 动态显示初始化界面
    	实现与用户交互功能
组件通信的5种方式
	props
	vue的自定义事件
	pubsub第三方库
	slot
	vuex(后面单独讲)
props:
    父子组件间通信的基本方式
    属性值的2大类型: 
        一般: 父组件-->子组件
        函数: 子组件-->父组件
	隔层组件间传递: 必须逐层传递(麻烦)
	兄弟组件间: 必须借助父组件(麻烦)
vue自定义事件
    子组件与父组件的通信方式
    用来取代function props
    不适合隔层组件和兄弟组件间的通信
pubsub第三方库(消息订阅与发布)
    适合于任何关系的组件间通信
slot
    通信是带数据的标签
    注意: 标签是在父组件中解析
vuex
    多组件共享状态(数据的管理)
    组件间的关系也没有限制
    功能比pubsub强大, 更适用于vue项目

4. ajax

相关库:
    vue-resource: vue插件, 多用于vue1.x
    axios: 第三方库, 多用于vue2.x
vue-resource使用
    // 引入模块
    import VueResource from 'vue-resource'
    // 使用插件
    Vue.use(VueResource)
    
    // 通过vue/组件对象发送ajax请求
    this.$http.get('/someUrl').then((response) => {
      // success callback
      console.log(response.data) //返回结果数据
    }, (response) => {
      // error callback
      console.log(response.statusText) //错误信息
    })
axios使用
    // 引入模块
    import axios from 'axios'
    
    // 发送ajax请求
    axios.get(url)
      .then(response => {
        console.log(response.data) // 得到返回结果数据
      })
      .catch(error => {
    	console.log(error.message)
      })

5. vue-router

vue用来实现SPA的插件
使用vue-router
    1. 创建路由器: router/index.js
      new VueRouter({
        routes: [
          { // 一般路由
            path: '/about',
            component: about
          },
          { // 自动跳转路由
            path: '/', 
            redirect: '/about'
          }
        ]
      })
    2. 注册路由器: main.js
       import router from './router'
       	new Vue({
       		router
       	})
    3. 使用路由组件标签:
       	<router-link to="/xxx">Go to XXX</router-link>
       	<router-view></router-view>
编写路由的3步
    1. 定义路由组件    
    2. 映射路由
    3. 编写路由2个标签
嵌套路由
    children: [
        {
          path: '/home/news',
          component: news
        },
        {
          path: 'message',
          component: message
        }
     ]
向路由组件传递数据
    params: <router-link to="/home/news/abc/123">
    props: <router-view msg='abc'>
缓存路由组件
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
路由的编程式导航
	this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
	this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
	this.$router.back(): 请求(返回)上一个记录路由

6.项目中遍历产生index头部导航需要保存在localstroage中


 export default {
    data(){
      return{
        Index:0
      }
    },
    computed:{
      ...mapState([
     'headCateList',

      ])
    },
    mounted(){
      this.$store.dispatch('getHeadCateList',()=>{
        this.$nextTick(()=>{
          PubSub.subscribe('headerData',(msg,data)=>{
            this.Index=data
            console.log(data)
          })
      });

      })
    },
    //消息订阅与发布需要在生命周期被销毁时取消订阅,避免重复订阅
    destroyed(){
      PubSub.unsubscribe('headerData')


    },
    updated(){
      const index =this.Index;
      localStorage.setItem("setActiveId",index)
    },
    beforeMount(){
      const nowIndex = localStorage.getItem("setActiveId")
      this.Index=nowIndex
    }

  }

7.两个子组件间传递index信息,利用消息订阅与发布,把index传给需要的组件,需要的组件订阅消息

有index信息的组件发布消息,先订阅再发布,例子如下:

###1)需要数据的组件订阅消息,先订阅


export default {
    data(){
      return{
        Index:0
      }
    },
    computed:{
      ...mapState([
     'headCateList',

      ])
    },
    mounted(){
      this.$store.dispatch('getHeadCateList',()=>{
        this.$nextTick(()=>{
         + PubSub.subscribe('headerData',(msg,data)=>{
         +   this.Index=data
         +   console.log(data)
          })
      });

      })
    },

###2)有数据的组件发布消息,发布事件名与订阅事件名要一致


<template>
  <div class="header_wrapper">
    <div class="large_header">
      <div  class="header">
        <div class="logo">
          <img src="./images/logo.png" alt="" @click="$router.replace('/msite')">
        </div>
        <div class="search">
          <i class="iconfont icon-search"></i>
          <span class="placeholder">搜索商品, 共10718款好物</span>
        </div>
      </div>
      <div class="nav_wrapper" ref="nav">
        <ul class="slide_nav">
          <li class="slide_item" @click="goIn({path:'/msite/recommend',index:activeIndex})" :class="{active:$route.path ==='/msite/recommend'}" >推荐</li>
          <li class="slide_item" @click="goIn({path:'/msite/athome',index})" :class="{active: index==activeIndex }"
            v-for="(headCate,index) in headCateList" :key="index"
          ></li>
        <!--  <li class="slide_item">鞋包配饰</li>
          <li class="slide_item">服装</li>
          <li class="slide_item">电器</li>
          <li class="slide_item">洗护</li>
          <li class="slide_item">饮食</li>
          <li class="slide_item">餐厨</li>
          <li class="slide_item">婴童</li>
          <li class="slide_item">文本</li>
          <li class="slide_item">特色区</li>-->
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  import BScroll from 'better-scroll'
  import {mapState} from 'vuex'
  import PubSub from 'pubsub-js'
  export default {
    data () {
      return{
        activeIndex:-1,
      }
    },
    computed:{
      ...mapState(['headCateList']),
    mounted(){
     this.$nextTick(()=>{
       this.navsScroll=new BScroll('.nav_wrapper',{
         probeType: 2,
         scrollX:true,
         click: true,
         eventPassthrough:'vertical'
       })
     })
    },
    updated(){
      const index =this.activeIndex;
      localStorage.setItem("setActiveId",index)
    },
    beforeMount(){
      const nowIndex = localStorage.getItem("setActiveId")
      this.activeIndex=nowIndex
    },
    methods:{
      goIn(obj){
        let {path,index}=obj
        this.$router.push(path)
        this.activeIndex =index
        PubSub.publish('headerData',index)
      }
    },
  }

###1)App引入的底部需配置显示隐藏meta来控制各个路由的显示隐藏


 <Footer v-show="$route.meta.showFooter"/>


###2)在管理路由器的router文件的index.js配置meta控制底部footer,显示隐藏

 {
      path: '/msite',
      component:Msite,
      meta:{
        showFooter:true
      },



Comments

Content