本文最后更新于255 天前,其中的信息可能已经过时,如有错误请发送邮件到zhizihua030611@163.com
脚手架结构分析:
文件目录
├── 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:
vue.js 与 vue.runtime.xxx.js的区别:
vue.js 是完整版的 Vue,包含:核心功能+模板解析器
vue.runtime.xxx.js 是运行版的 Vue,只包含核心功能,没有模板解析器
vue.config.js配置文件:
vue.config.js 是一个可选的配置文件,如果项目的(和 package.json 同级的)根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载
使用 vue.config.js 可以对脚手架进行个性化定制,详见https://cli.vuejs.org/zh/config/#vue-config-js参考
ref属性:
1.被用来给元素或子组件注册应用信息(id的替代者)
2.应用再html标签上获取的真实DOM元素,应用在组件标签上是组件实例对象
3.使用方式:
打标识:<h1 ref='xxx'>....</h1> 或 <School ref='xxx'><School>
获取:this.$refs.xxx
prop配置:
props配置项:
功能:让组件接收外部传过来的数据
传递数据:<Demo name="xxx"/>
接收数据:
1.简单声明接收
2.接收的同时对数据进行类型限制
props:{
name:String,
age:Number,
sex:String
}
3.接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
props:{
name:{
type:String, //name的类型是字符串
required:true, //name是必需的
},
age:{
type:Number,//name的类型是字符串
default:99//默认值,若不传则是这个值
},
sex:{
type:String,
required:true
}
}
props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据
mixin(混入)
功能:可以把多个组件公用的配置提取成一个而混入对象
使用方式:
第一步定义混合,例如:
{
data(){...},
methods:(...)
...
}
第二步使用混入,例如:
(1).全局混入:Vue.mixin(xxx)
(2).局部混入:mixins:['xxx']
plugin插件
功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
使用插件:Vue.use(plugin)
scoped样式
作用:让样式在局部生效,防止冲突
写法:<style scoped>
scoped样式一般不会在App.vue中使用
TodoList案例
组件化编码流程:
拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突
实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:
一个组件在用:放在组件自身即可
一些组件在用:放在他们共同的父组件上(状态提升)
实现交互:从绑定事件开始
props适用于:
父组件 ==> 子组件 通信
子组件 ==> 父组件 通信(要求父组件先给子组件一个函数)
使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的
props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做
WebStorage
存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
浏览器端通过Window.sessionStorage和Window.localStorage属性来实现本地存储机制
相关API:
xxxStorage.setItem('key', 'value'):该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
xxxStorage.getItem('key'):该方法接受一个键名作为参数,返回键名对应的值
xxxStorage.removeItem('key'):该方法接受一个键名作为参数,并把该键名从存储中删除
xxxStorage.clear():该方法会清空存储中的所有数据
备注:
SessionStorage存储的内容会随着浏览器窗口关闭而消失
LocalStorage存储的内容,需要手动清除才会消失
xxxStorage.getItem(xxx)如果 xxx 对应的 value 获取不到,那么getItem()的返回值是null
JSON.parse(null)的结果依然是null
组件的自定义事件
一种组件间通信的方式,适用于:==子组件 > 父组件
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)
绑定自定义事件:
第一种方式,在父组件中:<Demo @atguigu="test"/> 或 <Demo v-on:atguigu="test"/>
第二种方式,在父组件中:
<Demo ref="demo"/>
...
mounted(){
this.$refs.demo.$on('atguigu',data)
}
若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法
触发自定义事件:this.$emit('atguigu',数据)
解绑自定义事件:this.$off('atguigu')
组件上也可以绑定原生DOM事件,需要使用native修饰符
注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
全局事件总线
一种组件间通信的方式,适用于任意组件间通信
安装全局事件总线:
new Vue({
...
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
},
...
})
使用事件总线:
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
export default {
methods(){
demo(data){...}
}
...
mounted() {
this.$bus.$on('xxx',this.demo)
}
}
提供数据:this.$bus.$emit('xxx',data)
最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
消息订阅与发布
消息订阅与发布(pubsub):
消息订阅与发布是一种组件间通信的方式,适用于任意组件间通信
使用步骤:
安装pubsub:npm i pubsub-js
引入:import pubsub from 'pubsub-js'
接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
export default {
methods(){
demo(data){...}
}
...
mounted() {
this.pid = pubsub.subscribe('xxx',this.demo)
}
}
提供数据:pubsub.publish('xxx',data)
最好在beforeDestroy钩子中,使用pubsub.unsubscribe(pid)取消订阅
$nextTick:
语法:this.$nextTick(回调函数)
作用:在下一次 DOM 更新结束后执行其指定的回调
什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行
Vue封装的过渡与动画
作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名
图示:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F7tX8Utw-1648820283412)(https://cn.vuejs.org/images/transition.png)]
写法:
准备好样式:
元素进入的样式:
v-enter:进入的起点
v-enter-active:进入过程中
v-enter-to:进入的终点
元素离开的样式:
v-leave:离开的起点
v-leave-active:离开过程中
v-leave-to:离开的终点
使用<transition>包裹要过度的元素,并配置name属性:
<transition name="hello">
<h1 v-show="isShow">你好啊!</h1>
</transition>
备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值
vue脚手架配置代理服务器
方法一:
在vue.config.js中添加如下配置:
devServer:{
proxy:"http://localhost:5000"
}
说明:
优点:配置简单,请求资源时直接发给前端即可
缺点:不能配置多个代理,不能灵活的控制请求是否走代理
工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
方法二:
devServer: {
proxy: {
'/api1': { // 匹配所有以 '/api1'开头的请求路径
target: 'http://localhost:5000',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api1': ''}
},
'/api2': { // 匹配所有以 '/api2'开头的请求路径
target: 'http://localhost:5001',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api2': ''}
}
}
}
// changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
// changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
说明:
优点:可以配置多个代理,且可以灵活的控制请求是否走代理
缺点:配置略微繁琐,请求资源时必须加前缀
插槽
1.作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件 ===> 子组件,
2.分类:默认插槽、具名插槽、作用于插槽
3.使用方式:
1.默认插槽
父组件中:
<Category>
<div>html结构</div>
</Category>
子组件中:
<template>
<div>
<solt>插槽默认内容...</solt>
</div>
</template>
2.具名插槽
父组件中:
<Category>
<template solt='name1'>
<div>html结构1</div>
<template>
<template v-solt:name2>
<div>html结构2</div>
<template>
</Category>
子组件中:
<template>
<div>
<solt name='name1'>插槽默认内容...</solt>
<solt name='name2'>插槽默认内容...</solt>
</div>
</template>
3.作用域插槽
1.理解:数据再组件的自身,但根据数据生成的结构需要组件的使用者来决定
2.具体编码
父组件中:
<Category>
<template scope="scopeData">
<!-- 生成的是ul列表 -->
<ul>
<li v-for="g in scopeData.games" :key="g">{{g}}</li>
</ul>
</template>
</Category>
<Category>
<template slot-scope="scopeData">
<!-- 生成的是h4标题 -->
<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
</template>
</Category>
子组件中:
<template>
<div>
<slot :games="games"></slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title'],
//数据在子组件自身
data() {
return {
games:['红色警戒','穿越火线','劲舞团','超级玛丽']
}
},
}
</script>
Vuex

1.什么时候使用Vuex
多个组件依赖于同一状态
来自不同组件的行为需要变更同一状态
2.Vuex工作原理图

3.总结:
getters配置项的使用:
1.概念:当state中的数据需要经过加工后再使用时,可以使用getters加工
2.在store.js中追加getters配置
...
const getters = {
bigSum(state){
return state.sum * 10
}
}
//创建并暴露store
export default new Vuex.Store({
...
getters
})
3.组件中读取数据:$store.getters.bigSum
四个map
1.mapState方法:用于帮助我们映射state中的数据
computed: {
//借助mapState生成计算属性:sum、school、subject(对象写法)
...mapState({sum:'sum',school:'school',subject:'subject'}),
//借助mapState生成计算属性:sum、school、subject(数组写法)
...mapState(['sum','school','subject']),
},
2.mapGetters方法:用于帮助我们映射getters中的数据
computed: {
//借助mapGetters生成计算属性:bigSum(对象写法)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性:bigSum(数组写法)
...mapGetters(['bigSum'])
},
3.mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数
methods:{
//靠mapActions生成:incrementOdd、incrementWait(对象形式)
...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
//靠mapActions生成:incrementOdd、incrementWait(数组形式)
...mapActions(['jiaOdd','jiaWait'])
}
4.mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数
methods:{
//靠mapActions生成:increment、decrement(对象形式)
...mapMutations({increment:'JIA',decrement:'JIAN'}),
//靠mapMutations生成:JIA、JIAN(对象形式)
...mapMutations(['JIA','JIAN']),
}
备注:mapActions与mapMutations使用时,若需要传递参数,则需要在模板中绑定事件时传递好参数,否则参数是事件对象
axios
api/index
get写法(异步写请求里面)
import axios from "axios";
export const GetUserInfoServer = async () => {
const url = 'http://127.0.0.1:5000/Home';
try {
const response = await axios.get(url);
console.log(response.data.data);
return response.data;
} catch (error) {
console.error('Error fetching user info:', error);
throw error; // 重新抛出错误,以便调用者可以捕获并处理它
}
};
组件中使用
const GetuserInfo = async() =>{
const result = GetUserInfoServer()
.then(data =>{
userinfo.value = data.data
console.log('userinfo:',userinfo.value)
})
.catch(error =>{
console.log('error:',error)
})
}
GetuserInfo()
post写法(异步写方法里面)
import axios from "axios";
export const postUsernameServer = (username,password) => {
const url = 'http://127.0.0.1:5000/user_info';
const data = {
username: username,
password: password
};
const res = axios.post(url, data)
.then(response => {
console.log(response.data.data)
return response.data;
})
.catch(error => {
console.error('Error posting username and fetching users:', error);
throw error; // 重新抛出错误,以便调用者可以捕获并处理它
});
return res
};
组件中使用
const Login = async () => {
if (!username.value) {
alert('请输入用户名!');
return;
}
try {
const result = await postUsernameServer(username.value, password.value);
if (result) {
console.log('登录成功')
console.log(result)
console.log('-------------')
console.log(result.data)
UserStore.setUser(result.data)
console.log('------------')
console.log(UserStore.user.avatar)
router.push('/pig-car/home')
} else {
console.log('请确认用户名和密码是否正确')
}
} catch (err) {
console.error('检查用户名时出错:', err.message);
}
};


