webpack+vue+ element ui +vueX+axios 开发项目注意点及知识点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gao_xu_520/article/details/79686945

一.小知识点

1.项目中`.`和`@`的区别

./这是相对路径的意思。
@/这是webpack设置的路径别名。
这东西在vue标准模板里面的build/webpack.base.conf这个文件里面。
resolve: {
    // 路径别名
    alias: {
        '@': resolve('src'),
        'vue$': 'vue/dist/vue.esm.js'
    }
},
就是说@这东西代表着到src这个文件夹的路径

2.指令 (Directives) 是带有 v- 前缀的特殊属性

指令属性的值预期是单个 JavaScript 表达式 。指令的职责是,当表达式的值改变时,将其产生的连带影响,响应式地作用于 DOM。

Vue.js 为 v-bind 和 v-on 这两个最常用的指令,提供了特定简写:
v-bind 缩写
<!-- 完整语法 -->
<a v-bind:href="url">...</a>
<!-- 缩写 -->
<a :href="url">...</a>

v-on 缩写
<!-- 完整语法 -->
<a v-on:click="doSomething">...</a>

<!-- 缩写 -->
<a @click="doSomething">...</a>

3.修饰符(Modifiers)

 是以半角句号 . 指明的特殊后缀,用于指出一个指令应该以特殊方式绑定。例如,.prevent 修饰符告诉 v-on 指令对于触发的事件调用 event.preventDefault():

<form v-on:submit.prevent="onSubmit">...</form>

参考:vue.js事件修饰符(阻止冒泡 默认行为)

4.父组件引用子组件的页面

<template>
	<div id="father">
    <child></child>
	</div>
</template>


<script>
  import child from '/child'
export default {
    name: 'father',
    components:{
		child
    }
}
</script>

5.定义全局变量和全局函数

(1).用export default 暴露

①创建assets里面创建base.js  

const serverSrc='www.baidu.com'
function Test1() {
	console.log('注册全局函数')
}
export default{
	serverSrc,
	Test1
}

②在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值

import base from '@/assets/js/base'
export default {
	methods: {
		add(){
			console.log('点击')
			base.Test1();
			console.log(base.serverSrc)
		}
	}
}

(2).全局变量模块挂载到Vue.prototype 里

①创建assets里面创建base.js :

//全局变量和全局函数js
exports.install = function (Vue, options) {
    Vue.prototype.text1 = function (){//全局函数1
        console.log('执行成功1');
    };
     // 重置表单内的元素
    Vue.prototype.resetForm =function (selector){
        $(':input', selector)
            .not(':button, :submit, :reset, :hidden')
            .val('').change()
            .removeAttr('checked')
            .removeAttr('selected');
        if (typeof (handler) === "function") {
            handler();
        }
    };
    Vue.prototype.serverSrc='www.baidu.com';
};

②在mainjs注册

import base from '@/assets/js/base'
Vue.use(base);//将全局函数当做插件来进行注册

③在组件页面中使用: 用this

this.resetForm(".userform"); 

6.Vue2 实例中的 data 属性三种写法与作用

var app = new Vue({  
  // 1.  
  // data () {  
  //   return {count: 0}  
  // },  
  
  // 2.  
  // data: {  
  //   count: 0  
  // },  
  
  // 3.  
  data: function() {  
    return {  
      count: 0  
    }  
  },  
  
  methods: {  
    inc () {this.count++}  
  }  
})  

注意:在简单的练习 或者直接引vue.js的实例 都行 ,但是在大型项目使用1种。简而言之,在app = new Vue对象时,没什么区别,因为你app对象不会被复用。但是在组件中,因为可能在多处调用同一组件,所以为了不让多处的组件共享同一data对象,只能返回函数

7.svg转成图标字体的制作方法

打开icomoon的官网 ---->点击import icons  ---->选中我们的svg 图标---->选中这些图标 ----> 点击generate Font F(左下角的按钮)---->点击 Preferences (设置文件名  生成图标字体的文件名称)---->  Download 下载---->使用的时候: 选中fonts和style.css 放在项目中


8.Vue中的常用选项

(1)、计算属性
computed为可以计算的属性,由get方法和set方法组成,默认调用的是get方法。里面的
计算属性简单来说,就是根据数据推算出来的值,当给这个值赋值时可以影响其他值的变化。

<div id="app">
  全选:<input type="checkbox" v‐model="checkAll" > <br>
  <input type="checkbox" v‐for="a in checkList" v‐model="a.selected">
  </div>
  data:{
checkList:[{selected:true},{selected:true},{selected:false}]
  },
  computed:{
   checkAll:{
set(val){//此处的val代表的就是全选键的值。

    for(var arr of this.checkList){
        arr.selected = val;
       }
   },
    get(){
       var obj = this.checkList.find(function (item) {
           return !item.selected
       });
           return obj?false:true;
   }
 }
 msg:function(){return }//默认是get
  }
(2)、methods
定义一些方法,供组件使用。
(3)、watch
用于检测的数据发生改变的api
和computed不同,watch可以夹杂异步逻辑

当一个值发生变化的时候,执行某个动作用watch更加方便。

<div id="app">
  <input type="text" v‐model="msg">
  {{content}}
  </div>
  var vm = new Vue({
 el:'#app',
  data:{
     msg:'hello',
     content:''
  },
  watch:{
      msg:function () {
          this.content = 'waiting...';
          setTimeout(()=> {
              this.content = 'Hello Mrs Jiang!'
          },2000);
      }
  }
  });//修改msg的值先等待两秒后再显示。
  computed适合做复杂逻辑,简单的只能给watch,当一个值改变触发某个事件时使用watch;如果是异步,并且有中间过程,用watch。
(4)、data

每个 Vue 实例都会代理其 data 对象里所有的属性

var data = { a: 1 }
var vm = new Vue({
data: data
})
vm.a === data.a   // -> true
vm.a = 2          // 设置属性也会影响到原始数据
data.a            // -> 2
data.a = 3        // ... 反之亦然
vm.a              // -> 3
注意:只有这些被代理的属性是响应的。如果在实例创建之后添加新的属性到实例上,它不会触发视图更新

除了 data 属性, Vue 实例暴露了一些有用的实例属性与方法。这些属性与方法都有前缀 $,以便与代理的 data 属性区分。

var data = { a: 1 }
var vm = new Vue({
  el: '#example',
  data: data
})
vm.$data === data       // -> true
vm.$el === document.getElementById('example') // -> true
vm.$watch('a', function (newVal, oldVal) { // $watch 是一个实例方法
  // 这个回调将在 `vm.a`  改变后调用
})
注意:不要在实例属性或者回调函数中(如 vm.$watch('a', newVal => this.myMethod()))使用箭头函数。因为箭头函数绑定父上下文,所以 this 不会像预想的一样是 Vue 实例,而是 this.myMethod 未被定义

9.动态绑定类名

动态绑定的class和原生的class可以共存,如果有覆盖,动态的覆盖静态的。

1、对象绑定方式:
:class="{类名:条件,类名:条件}"
如果条件为true,添加样式;如果条件为false,移除样式。
2、数组绑定方式:
:class="[data中的数据,"类名",{类名:条件}]"
data:{
data中的数据:“类名”,
}

10.动态绑定style

1、对象绑定方式:
:style="{属性名:属性值}"
2、数组绑定方式:
:style="[data中的数据]"
data:{
data中的数据:{属性名:属性值}
}

11.字符串拼接

之前定义字符串是:var str=""; 或是var str='';  字符串的拼接:‘abc'+变量名+'ef'

现在 使用的是反单引号 : var str=``;这是模板字符串   字符串的拼接:`abc${变量名}ef`

//之前  
        var a='老师';  
        var b='不忘初心';  
        var str=a+'说:“'+b+'、继续前进!”';  
        document.write(str);//老师说:不忘初心、继续前进!”  
  
  
        //现在  
        var a='老师';  
        var b='不忘初心';  
        var str=`${a}说:${b}、继续前进!”`;  
  
        document.write(str);//老师说:不忘初心、继续前进!”</span></span>  

12.设置当前路由默认跳转那个--redirect


注意:同时也可以修改路由高亮的类名 linkExactActiveClass:'active'

13

二.vue使用过程中遇到的错误

1.错误提示:template syntax error Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead. 
翻译结果:模板语法错误组件模板应该正好包含一个根元素,如果你使用的是v-if多元素,使用v-else-if链他们。
错误原因:vue模板只支持一个元素,不能并列包含两个及以上。
代码中< template />标签下包含了2个控件,这是vue不支持的。

解决办法:在并列控件的最外层加上< div>< /div> 


三.vuex注意点

1.读取状态最简单的方法就是在计算属性中返回某个状态

是在根实例(main.js)中注册 store 选项,所以子组件能通过 this.$store访问到

<template>
    <h4>Count is {{count}}</h4>
</template>

<script>
import { mapState } from 'vuex'
export default {
	computed:{
		count(){
		    return this.$store.state.count
		}
	}
}
</script>

注意:

 this.$store取vuex公共数据 

2.mapState 辅助函数:当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。如count

3.更改  store 中的状态的唯一方法是 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

通过 store.commit 方法触发mutation的方法.如:this.$store.commit('increment');

4.异步逻辑都应该封装到 action 里面

5.vue组件中的样式属性--scoped

vue组件中的style标签标有scoped属性时表明style里的css样式只适用于当前组件元素 

<style scoped>
.example {
  color: red;
}
</style>

渲染结果:
<style>
.example[data-v-f3f3eg9] {
  color: red;
}
</style>

混合使用全局属性和局部属性

<style>
/* global styles */
</style>

<style scoped>
/* local styles */
</style>

6.使用prop传值

在子页面接受值时,需要在props 那边定义类型:如

父页面:<v-shopcart :delivery-price="seller.deliveryPrice" :min-price="seller.minPrice"></v-shopcart>

子页面: type: Number,//类型  default: 0 默认值

<div class="desc">¥{{deliveryPrice}}元</div>
export default {
	props: {
		deliveryPrice: {
	        type: Number,
	        default: 0
	    },
	    minPrice: {
	        type: Number,
	        default: 0
	    }
	}
}

四.在vue项目中引用

1.vue项目中使用阿里iconfont图标

(1).阿里字体库Iconfont--找自己需要的图片--下载到本地

(2).引用字体图片

a.在vue项目中 static中引用 


b.在index.html中引用  :<link rel="stylesheet" type="text/css" href="./static/font/iconfont.css">

在index.vue 引用:<i class="iconfont icon-alignjustify"></i>

3.element-ui中下拉菜单子选项click事件不触发问题

解决方式:@click改为@click.native

<el-dropdown split-button type="primary" @click="btnSearch">
	检索
	<el-dropdown-menu slot="dropdown">
		<el-dropdown-item @click.native="btnReset">重置</el-dropdown-item>
	</el-dropdown-menu>
</el-dropdown>


export default {
	methods: {
		//检索
		btnSearch(){
			console.log('检索')
		},
		//重置
		btnReset(){
			console.log('重置')
		}
		
	}
}

2.路由文件夹内的路由文件引用

1在router创建menus.Router.js
2.在路由入口文件index.js 引用
export default new Router({
	routes: [
		{
			path: '/',
			name: 'index',
			component: Index,
			hidden: true,
			children:[
				require('./menus.Router').default
			]
		}
	]
})
3.在在menus.Router.js  文件处
// 引入页面组件
import leftMenu from '@/components/public/leftMenu'
//定义路由
export default{
    path: '/leftMenu', 
    component: leftMenu 
}

测试:
在index.vue:<router-link to="/leftMenu">菜单:</router-link>
在leftMenu.vue :<template>测试leftMenu</template>

3.图片懒加载

A.首先引入vue 图片懒加载的插件vue-lazyload 

插件地址:https://github.com/hilongjw/vue-lazyload

demo:http://hilongjw.github.io/vue-lazyload/

安装插件:找到项目 执行命令 npm install vue-lazyload --save-dev

B.在main.js引入

//图片懒加载:滚到图片才加载 没滚到的时候图片是白色
import VueLazyLoad from 'vue-lazyload'
//图片懒加载 引入加载图片
Vue.use(VueLazyLoad,{
    loading:'./static/loading-svg/loading-bars.svg'//是加载的图片
})
C. vue文件中将需要懒加载的图片绑定 v-bind:src 修改为 v-lazy 

<img class="item-pic" v-lazy="newItem.picUrl"/>

4.vue 插入视频

H5的video标签不能直接在vue里使用,需要安装其他插件,vue-video-player  兼容ie9以上(不过ie9的时候样式会有点乱)

官网案例

A.安装依赖: npm install vue-video-player  --save

B.引入配置main.js

import VideoPlayer from 'vue-video-player'
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')
Vue.use(VideoPlayer)

c.vue组件中

<template>
	<div>
		<video-player  class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true" :options="playerOptions"></video-player>
	</div>
</template>
<script>
export default {
	data () {
		return {

	        playerOptions: {
	        	height: '270',
		        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
		        autoplay: false, //如果true,浏览器准备好时开始回放。
		        muted: false, // 默认情况下将会消除任何音频。
		        loop: false, // 导致视频一结束就重新开始。
		        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频(如果浏览器支持)
		        language: 'zh-CN',
		        aspectRatio: '16:9', // 将播放器置于流畅模式,并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字(例如"16:9"或"4:3")
		        fluid: true, // 当true时,Video.js player将拥有流体大小。换句话说,它将按比例缩放以适应其容器。
		        sources: [{
		           	type: "video/mp4",
		          	src: "http://vjs.zencdn.net/v/oceans.mp4" //url地址
		        }],
		        poster: "https://surmon-china.github.io/vue-quill-editor/static/images/surmon-1.jpg", //你的封面地址
		        // width: document.documentElement.clientWidth,
		        notSupportedMessage: '此视频暂无法播放,请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
		        controlBar: {
					timeDivider: true,
					durationDisplay: true,
					remainingTimeDisplay: false,
					fullscreenToggle: true  //全屏按钮
		        }
    		}
		}
	}
    }
}
</script>

5.vue-awesome-swiper(轮播图vue插件)

轮播图插件,可以同时支持Vue.js(1.X ~ 2.X),兼顾PC和移动端,SPA和SSR。

案例

github代码

注意:这个只能兼容ie10

A.安装vue-awesome-swiper

npm install vue-awesome-swiper --save

B.vue挂载  mian.js

import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
 
import 'swiper/dist/css/swiper.css'
//在 Vue.use(VueAwesomeSwiper)之前,要先引入样式 import 'swiper/dist/css/swiper.css'
Vue.use(VueAwesomeSwiper, /* { default global options } */)

C.组件中使用

<template>
	<swiper :options="swiperOption">
		<swiper-slide v-for="(item,index) in news" :key="item.moduleId">
			<img :src="item.pic" :alt="item.title"/>
		</swiper-slide>
		<div class="swiper-pagination" slot="pagination"></div>
	</swiper>
</template>									
export default {
	data () {
		return {
			swiperOption: {
				autoplay: true,//自动
				setWrapperSize :true,
				pagination: {//按钮
		            el: '.swiper-pagination',
		            clickable: true
		        },
				mousewheelControl : true,
				observeParents:true
			}
		}
	}
}




猜你喜欢

转载自blog.csdn.net/gao_xu_520/article/details/79686945