Vue进阶总结,前端小白必知必会

118 阅读7分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天,点击查看活动详情

脚手架文件结构

├── node_modules 
├── public
│   ├── favicon.ico: 页签图标
│   └── index.html: 主页面
├── src
│   ├── assets: 存放静态资源
│   │   └── logo.png
│   │── component: 存放组件
│   │   └── HelloWorld.vue
│   │── App.vue: 汇总所有组件
│   │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件 
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

Vue项目的运行

配置npm淘宝镜像:npm config set registry https://registry.npm.taobao.org

第一步(仅第一次执行):全局安装@vue/cli。npm install -g @vue/cli

第二步:切换到你要创建项目的目录,cd ……进入项目目录

第三步:使用命令创建项目vue create vue_test(vue_test替换为你的项目名)

在这里插入图片描述

第四步:cd vue_test进入项目

第五步:npm run serve运行项目

第六步:在控制台按ctrl+c以终止项目 可以把练习过的案例复制一份,把案例改名存放,然后在src里开始新的项目。

在这里插入图片描述

关于不同版本的Vue:

1.vue.js与vue.runtime.xxx.js的区别: (1).vue.js是完整版的Vue,包含:核心功能+模板解析器。 (2).vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。

2.因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用 render函数接收到的createElement函数去指定具体内容。

vue.config.js配置文件

  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
  2. 使用vue.config.js可以对脚手架进行个性化定制,详情见:cli.vuejs.org/zh

ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx可用console.log(this.$refs.xxx)输出,等同于js里的document.getElementById(xxx)

mixin(混入)

  1. 功能:可以把多个组件共用的配置提取成一个混入对象,实现复用的目的。

  2. 如果data中的数据、methods中的方法原数据没有的就把混合的展示,原数据有的还展示原数据。

  3. 使用方式:

    第一步定义混合:

    export const hunhe{
        data(){....},
        methods:{....}
        ....
    }
    

mixin.js:

export const hunhe = {
	methods: {
		showName(){
			alert(this.name)
		}
	},
	mounted() {
		console.log('你好啊!')
	},
}
export const hunhe2 = {
	data() {
		return {
			x:100,
			y:200
		}
	},
}

第二步使用混入(两种方式):

​ 1.全局混入:把以下代码加在main.js里

import {hunhe,hunhe2} from './mixin'
Vue.mixin(hunhe)
Vue.mixin(hunhe2)

​ 2.局部混入:mixins:['hunhe'] Student.vue:

<template>
	<div>
		<h2 @click="showName">学生姓名:{{name}}</h2>
		<h2>学生性别:{{sex}}</h2>
	</div>
</template>

<script>
	import {hunhe,hunhe2} from '../mixin'
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男'
			}
		},
		mixins:[hunhe,hunhe2]
	}
</script>

插件

  1. 功能:用于增强Vue,定义后的插件可在全局使用。

  2. 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。

  3. 定义插件:

    对象.install = function (Vue, options) {
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入(合)
        Vue.mixin(....)
    
        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {...}
        Vue.prototype.$myProperty = xxxx
    }
    
  4. 使用插件:Vue.use()

plugins.js:

//定义插件
export default {
	install(Vue){
		//全局过滤器
		Vue.filter('mySlice',function(value){
			return value.slice(0,4)
		})
}

main.js:

//引入插件
import plugins from './plugins'
//应用(使用)插件
Vue.use(plugins)

scoped样式

  1. 作用:让样式在局部生效,防止不同.vue文件样式出现重名,导致冲突。
  2. 写法:把.vue文件中的style标签写成<style scoped></style>

nextTick

  1. 语法:this.$nextTick(回调函数)
  2. 作用:在下一次 DOM 更新结束后执行其指定的回调。
  3. 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。
  4. setTimeout(()=>{回调函数})也可以实现。

TodoList案例

在这里插入图片描述

  1. 组件化编码流程:

    ​ (1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。

    ​ (2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:

    ​ 1).一个组件在用:放在组件自身即可。

    ​ 2). 一些组件在用:放在他们共同的父组件上(状态提升)。

    ​ (3).实现交互:从绑定事件开始。

  2. props适用于:

    ​ (1).父组件 ==> 子组件 通信

    ​ (2).子组件 ==> 父组件 通信(要求父先给子一个函数)

  3. 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!

  4. props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。

Vue封装的过度与动画

在这里插入图片描述

  1. 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

  2. 写法:

    1. 准备好样式:

      • 元素进入的样式:
        1. v-enter:进入的起点
        2. v-enter-active:进入过程中
        3. v-enter-to:进入的终点
      • 元素离开的样式:
        1. v-leave:离开的起点
        2. v-leave-active:离开过程中
        3. v-leave-to:离开的终点
    2. 使用<transition>包裹要过度的元素,并配置name属性:(只有一个时,name属性可省略,样式里要写成默认的.v-enter-active{};不省略时在样式里要写成.hello-enter-active{},其中hello替换为name属性的值)

      <transition name="hello">
      	<h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    3. 若想让动画一上来就展示,则使用<transition>:appear="true"。注意要带冒号才会把等号后边看成表达式,不然就当成字符串了,也可直接简写为appear

       <transition :appear="true">
       	<h1 v-show="isShow">你好啊!</h1>
       </transition>
    
    1. 备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值。
<transition-group name="hello" appear>
	<h1 v-show="!isShow" key="1">你好啊!</h1>
	<h1 v-show="isShow" key="2">123!</h1>
</transition-group>

用法示例:

<template>
	<div>
		<button @click="isShow = !isShow">显示/隐藏</button>
		<transition name="hello" appear>
			<h1 v-show="isShow">你好啊!</h1>
		</transition>
	</div>
</template>

<script>
	export default {
		name:'Test',
		data() {
			return {
				isShow:true
			}
		},
	}
</script>
//写法1:动画
<style scoped>
	h1{
		background-color: orange;
	}
	.hello-enter-active{
		animation: zagiee 0.5s linear;
	}
	.hello-leave-active{
		animation: zagiee 0.5s linear reverse;
	}
	@keyframes zagiee {
		from{
			transform: translateX(-100%);
		}
		to{
			transform: translateX(0px);
		}
	}
</style>
//写法2:过渡
<style scoped>
	h1{
		background-color: orange;
	}
	/* 进入的起点、离开的终点 */
	.hello-enter,.hello-leave-to{
		transform: translateX(-100%);
	}
	.hello-enter-active,.hello-leave-active{
		transition: 0.5s linear;
	}
	/* 进入的终点、离开的起点 */
	.hello-enter-to,.hello-leave{
		transform: translateX(0);
	}

</style>

除此之外还可以使用第三方动画: 使用前先安装:npm install animate.css 可以在这个网址挑选动画

<template>
	<div>
		<button @click="isShow = !isShow">显示/隐藏</button>
		<transition-group 
			appear
			name="animate__animated animate__bounce"//固定的 
			enter-active-class="animate__swing"//进入动画挑选一个喜欢的复制类名写到这
			leave-active-class="animate__backOutUp"//离开动画挑选一个喜欢的复制类名写到这
		>
			<h1 v-show="!isShow" key="1">你好啊!</h1>
			<h1 v-show="isShow" key="2">123!</h1>
		</transition-group>
	</div>
</template>

<script>
	import 'animate.css'//引入
	export default {
		name:'Test',
		data() {
			return {
				isShow:true
			}
		},
	}
</script>

<style scoped>
	h1{
		background-color: orange;
	}
</style>

vue脚手架配置代理

浏览器向服务器请求数据,发送请求,服务器收到请求,把数据发给浏览器,但浏览器并没有把数据给我们,因为发送了跨域,以下是解决方式:

方法一

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。 ​ 在vue.config.js中添加如下配置:

devServer:{
  proxy:"http://localhost:5000"//把5000替换成要请求数据所在的服务器上
}

这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:5000。 说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理(本地有的资源不会走代理)。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

方法二

​ 编写vue.config.js配置具体代理规则:

module.exports = {
	devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径(写法:axios.get('http://localhost:8080/api1/students')).then(),加上的话则请求服务器,若请求资源在本地则不加,这样就灵活的控制请求是否走代理
        target: 'http://localhost:5000',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api1': ''}//地址重写,即凡是以/api1开头的把/api1变为空,使得服务器收到的请求是/students而非api1/students
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
/*
   changeOrigin设置为true时,表示说谎,不让服务器知道真实的本机地址,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,表示不说谎,让服务器知道真实的本机地址,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。
<template>
	<div>
		<button @click="getStudents">获取学生信息</button>
		<button @click="getCars">获取汽车信息</button>
	</div>
</template>

<script>
	//先用npm i axios安装;还有一种vue-resource
	import axios from 'axios'
	export default {
		name:'App',
		methods: {
			getStudents(){//要请求的资源在:http://localhost:5000/students,使用方式1把代理配置到5000了。
				axios.get('http://localhost:8080/students').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			},
			getCars(){//用的方式2,因为加了前缀api2
				axios.get('http://localhost:8080/api2/cars').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			}
		},
	}
</script>

VueUI组件库

1.移动端常用UI组件库

1.Vanthttps://youzan.github.io/vant 2.CubeUIhttps://didi.github.io/cube-ui 3.MintUIhttp://mint-ui.github.io

2.PC端常用UI组件库

1.ElementUIhttps://element.eleme.cn 2.IViewUIhttps://www.iviewui.com