代码拉取完成,页面将自动刷新
同步操作将从 Williams/Vue2_尚硅谷学习 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
1 vue.js 与 vue.runtime.xxx.js 区别
1) vue.js 是完整版的 Vue,包含核心功能+模板解析器
2) vue.runtime.xxx.js 是运行版的 Vue,只包含核心功能,没有模板解析器
2 因为 vue.runtime.xxx.js 没有模板解析器,所以不能使用 template 配置项,需要使用 render 函数
接收到的 creatElement 函数去指定具体内容
注意:vue文件的template有package.json的22行
第一步(仅第一次),全局安装@vue/cli
npm install -g @vue/cli
第二步,切换到需要创建项目的目录,创建项目
vue create xxx
第三步,启动项目
npm run serve
注意,若出现下载缓慢需要
npm config set registry https://registry.npm.taobao.org
脚手架隐藏了所有 webpack 相关的配置,具体查看
vue inspect > output.js
npm vue-cli-serice inspect > output.js
使用 vue.config.js 可以对脚手架进行个性化定制https://cli.vuejs.org/zh
├── 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: 应用描述文件
1 被用来给元素或组件注册引用信息(id替代者)
2 应用在HTML标签上获取真实DOM元素,应用在组件上是组件实例对象vc
3 使用
ref="xxx"
this.$refs.xxx
功能:让组件接收外部传入的数据
1)传递数据
<demo name="xxx"/>
2)接收数据
第一种:只接收
props:['name']
第二种:限制类型
props:{
name:String
}
第三种:限制类型+限制必要性+指定默认值
props:{
name:{
type:String,
required:true,
default:'老王'
}
}
备注:props是只读,Vue底层会监视对props的修改,如果对其修改就会发出警告,若业务需求需要修改,赋值props的内容到data函数一份,之后修改data中的数据即可
功能:可以把多个组件共用的配置取成一个混入对象
使用方式:
第一步定义混合,例如:
{
data(){....},
methods:{....}
....
}
第二步使用混入,例如:
1)全局混入:
import {mixin,mixin2} from './mixin'
Vue.mixin(mixin)
Vue.mixin(mixin2)
2)局部混入:
import { mixin, mixin2 } from "../mixin";
mixins:[mixin,mixin2]
功能:增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
定义插件:
对象.install=function(Vue,options){
1 全局过滤器
2 全局指令
3 配置全局混入
4 添加实例方法
}
使用插件:Vue.use(插件名,传递的数据)
作用:让样式在局部生效,防止不同组件样式名重复导致冲突
写法:<style scoped lang='css/less'>
自定义元素id,不重复
1 组件化编码流程:
(1)拆分静态组件:组件要按照功能点拆分。命名不要与html元素冲突
(2)实现动态组件:考虑好数据存放位置,数据是一个组件在用,还是一些组件在用
1)一个组件在用:放在组件自身即可
2)一些组件在用:放在他们共同的父组件上(状态提升)
(3)实现交互:绑定事件开始
2 props适用于:
(1)父组件==>子组件通信————数据、对象、函数等
(2)子组件==>父组件通信(需要父先给子一个函数)
3 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是只读,不可以修改
4 props传过来若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做
1 存储内容一般为5MB左右(不同浏览器可能不一样)
2 浏览器端通过Window.sessionStorage和Window.localStorage属性实现本地存储机制
3 相关API
1.local/sessionStorage.setItem('key','value')
接收一个键和值作为参数,把键值添加到存储中,若键名存在更新值
2.local/sessionStorage.getItem('key')
接收一个键名作为参数,返回对应值
3.local/sessionStorage.removeItem('key')
接受一个键名,把该键名从存储删除
4.local/sessionStorage.clear()
清空存储所有数据
4 备注:
1.sessionStorage存储内容会随着浏览器窗口关闭而消失
2.localStorage存储内容需要手动清楚才会消失
3.local/sessionStorage.getItem('key')如果对于value值获取不到,返回null
4.JSON.parse(null)仍然是null
1 组件间通信的方式,适用于————子组件==>父组件
另一种子==>父,父组件定义methods,props传递
2 使用场景:A是父组件,B是子组件,B给A传数据,那么就要在A中给B绑定自定义事件(事件回调在A中)
3 绑定自定义事件:
1)在父组件中:<Student @azhan="getStudentName" />或<Student v-on:azhan="getStudentName" />
getStudentName需要在父组件定义methods,子组件用this.$emit("azhan",数据)调用,传入数据
2)在父组件中:
<Student ref="student"/>
mounted(){
this.$refs.student.$on("azhan", this.getStudentName);
}
注意:一个父组件自定义事件,多个子组件都可以使用
4 触发自定义事件
this.$emit("azhan",数据)
5 解绑:
this.$off("azhan");
6 组件绑定原生DOM和ref冲突?使用native修饰
<StudentInfo ref="student" @click.native="show" />
7 注意:使用ref绑定自定义事件时,要么配置在methods中,要么使用箭头函数,否则this指向出现问题
this.$refs.student.$on("azhan", this.getStudentName); // 绑定自定义事件
// this.$refs.student.$once("azhan", this.getStudentName); // 绑定自定义事件,一次性
/*
若在上面的函数中写this
this.$refs.student.$once("azhan", function(name, ...params){
console.log(this)
})
this是student对应的vc
谁触发的该事件this就是谁
若写成箭头函数就可以了
this.$refs.student.$once("azhan", (name, ...params)=>{
console.log(this)
})
this指向App组件实例对象
1 一种组件间通信的方式,适用于任何组件间通信
2 安装全局事件总线:
new Vue({
el: "#app",
render: (h) => h(App),
beforeCreate() {
// 全局事件总线
// 安装全局事件总线
Vue.prototype.$bus = this;
},
});
3 使用全局事件总线:
1)提供数据:
methods: {
sendStudentName() {
this.$bus.$emit("hello", 666);
},
},
2)接收数据:A组件想要接收数据,在A组件给$bus绑定自定义事件,事件回调留在A组件自身
mounted() {
console.log("School", this);
this.$bus.$on("hello", (data) => {
console.log("我是School,已收到数据", data);
});
},
4 最好在beforeDestroy()钩子中,用$off解绑当前组件用到的事件
beforeDestroy() {
// 若销毁组件,应该取消绑定的全局自定义事件
this.$bus.$off("hello");
},
注意:父组件与子组件间通信使用自定义事件时,当组件消失,自身vc消失,连带着绑定的事件全部消失,所以不需要设置beforeDestroy()解绑
1 一种组件间通信的方式,适用于任意组件间通信
2 步骤:
1)安装pubsub
npm i pubsub-js
2)引入
import pubsub from 'pubsub-js'
3)接收数据:A组件想接收数据,在A组件订阅消息,订阅的回调留在A组件自身
mounted() {
// 订阅消息
this.pubId = pubsub.subscribe("hello", (msgName, data) => {
console.log("有人发布了hello消息,回调函数被执行");
console.log(msgName); // 即hello
// 若用function:this 是undefined
// 若用箭头函数:this 是school组件vc
console.log(this);
});
},
4)提供数据
// 发布消息
pubsub.publish("hello", 175);
5)最好在beforeDestroy钩子中,取消订阅
beforeDestroy() {
// 通过订阅id取消订阅
pubsub.unsubscribe(this.pubId);
},
1 语法:this.$nextTick(回调函数)
2 作用:在下一次DOM更新结束后执行指定回调
3 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,需要在nextTick所指定的回调函数执行
1 作用:插入、更新、移除DOM元素时,在合适的时候给元素添加样式类名
2 图示:
3 写法:
1)准备好样式:
元素进入样式:
——v-enter:进入的起点
——v-enter-active:进入过程中
——v-enter-to:进入的终点
元素离开的样式:
——v-leave:离开的起点
——v-leave-active:离开过程中
——v-leave-to:离开的终点
2)使用<transition>包裹要过渡的元素,并配置name属性
<transition name="hello" appear>
<h1 v-show="isShow">你好,我是阿占</h1>
</transition>
3)备注:若有多个元素需要过渡,需要使用<transition-group>,且每个元素指定key值
同源策略:
协议名、主机名、端口号
跨域:
1 cors
2 jsonp ———— script src只能解决get请求,不能解决post等请求
3 代理服务器
1)nginx
2)Vue-cli
————只能配置一个代理
devServer: {
proxy: "http://localhost:3000",
},
1 xhr ————最原始
2 jQuery————封装
3 axios
4 fetch ————和xhr平级
5 vue-resource ————对xhr的封装
相较于axios,维护不频繁,更推荐axios
1 作用:父组件向子组件指定位置插入html结构,是一种组件间通信方式
————适用于:父组件==>子组件
2 分类:默认插槽、具名插槽、作用域插槽
3 使用方式:
1)默认插槽:
父组件:
<CategoryVue title="游戏">
<div>HTML结构</div>
</CategoryVue>
子组件:
<template>
<div class="category">
<h3>{{ title }}分类</h3>
<slot>我是默认值,使用者没有传递内容时,我将会显示</slot>
</div>
</template>
2)具名插槽:
父组件:
<CategoryVue title="美食">
<template slot="center">
<div>HTML结构</div>
</template>
<template slot="footer">
<div>HTML结构</div>
</template>
</CategoryVue>
子组件:
<template>
<div class="category">
<slot name="center">我是中间插槽</slot>
<slot name="footer">我是底部插槽</slot>
</div>
</template>
3)作用域插槽:
a 理解:数据在组件自身(子组件),根据数据生成结构需要使用者(父组件)决定
b 代码:
父组件:
<CategoryVue>
<template scope="scopeData">
<ul>
<li v-for="(g, index) in scopeData.games" :key="index">{{ g }}
</li>
</ul>
</template>
</CategoryVue>
子组件:
<template>
<div">
<slot :games="games" msg="你好啊我是插槽传递数据"></slot>
</div>
</template>
<script>
export default {
name: "CategoryVue",
props: ["title"],
data() {
return {
games: ["LOL", "CF", "PUBG", "王者荣耀"],
};
},
};
</script>
1 概念:
在Vue实现集中式状态(数据)管理的一个Vue插件,对Vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任何组件间通信
2 何时使用:
多个组件需要共享数据时
3 搭建Vuex环境
1)创建文件:src/store/index.js
// 引入Vue
import Vue from 'vue';
// 引入vuex
import Vuex from "vuex";
// 应用Vuex
Vue.use(Vuex);
// 准备 actions ————用于响应组件中的动作
const actions = {};
// 准备 mutations ————用于操作数据 (state)
const mutations = {};
// 准备 state ————用于存储数据
const state = {};
// 创建store并暴露store/导出
export default new Vuex.Store({
actions,
mutations,
state,
});
2)在main.js创建vm时传入store配置项
// 引入store
import store from "./store";
new Vue({
el: "#app",
render: (h) => h(App),
// 配置store
store,
});
4 基本使用:
1)初始化数据state,配置actions、配置mutations,操作文件store.js
2)组件中读取vuex数据:
this.$store.state.sum
3)组件修改vuex数据:
this.$store.dispatch('actions的方法名',数据)
this.$store.commit('mutations的方法名',数据)
备注:若没有网络请求或其他业务逻辑,组件也可以越过actions,不写dispatch,直接写commit
5 getters使用:
1)当state的数据需要加工后再使用时,且需要多组件复用,可以使用getters加工
2)在store.js追加getters配置
const getters = {
bigSum(state) {
return state.sum * 10;
},
};
export default new Vuex.Store({
actions,
mutations,
state,
getters
});
3)组件读取数据:
this.$store.getters.bigSum
1 mapState,映射this.$store.state的数据为计算属性
computed: {
// 借助mapState生成计算属性,从state映射数 据(对象写法)
...mapState({ he: "sum", xuexiao: "school", xueke: "subject" }),
// 数组写法,生成的计算属性名和读取出的名 要一致
...mapState(["sum", "school", "subject"]),
},
2 mapGetters,映射this.$store.getters数据为计算属性
computed: {
// 借助mapGetters生成计算属性,从getters 读取数据,对象、数组写法
...mapGetters({ bigSum: "bigSum" }),
...mapGetters(["bigSum"]),
},
3 mapActions,生成actions对话,包含$store.dispatch(xxx)的数据
methods:{
// 借助mapActions生成对应方法,方法会调用dispatch联系actions
...mapActions({ incrementOdd: "jiaOdd", incrementWait: "jiaWait" }),
...mapActions(["jiaOdd", "jiaWait"]),
}
4 mapMutations,生成与mutations对话的方法,包含$store.commit(xxx)数据
methods:{
// 借助mapMutations生成对应方法,方法会调用commit联系mutations
...mapMutations({ increment: "JIA", decrement: "JIAN" }),
...mapMutations(["JIA", "JIAN"]),
}
注意:mapActions和mapMutations需要穿参数,在模板绑定事件时传参,否则参数是事件对象(鼠标点击等)
1 目的:让代码更好维护,多种数据分类更加明确
2 修改store.js
// 求和功能相关配置
export default {
// true会被mapState('countOptions',['JIA])识别
namespaced: true,
actions: {
jiaOdd(context, value) {
if (context.state.sum % 2) {
context.commit("JIA", value);
}
},
jiaWait(context, value) {
setTimeout(() => {
context.commit("JIA", value);
}, 500);
},
},
mutations: {
JIA(state, value) {
state.sum += value;
},
JIAN(state, value) {
state.sum -= value;
},
},
state: {
sum: 0,
school: "石大",
subject: "前端",
},
getters: {
bigSum(state) {
return state.sum * 10;
},
},
};
3 开启命名空间后,组件读取state数据
...mapState("countAbout", ["sum", "school", "subject"], "personAbout", [
"personList",
]),
或
sum() {
return this.$store.state.countAbout.sum;
},
4 开启命名空间后,组件读取getter数据
return this.$store.getters["personAbout/firstPersonName"];
或
...mapGetters("countAbout", ["bigSum"]),
5 开启命名空间后,组件调用 dispatch
this.$store.dispatch("personAbout/addPersonWang", personObj);
或
...mapActions("countAbout", {
incrementOdd: "jiaOdd",
incrementWait: "jiaWait",
}),
6 开启命名空间后,组件调用commit
this.$store.commit("personAbout/ADD_PERSON", personObj);
或
...mapMutations("countAbout", { increment: "JIA", decrement: "JIAN" }),
1 SPA应用
single page web application
单页web应用
整个应用只有一个完整页面
不刷新页面,局部更新
数据通过ajax请求获取
2 路由:
一个路由就是一组映射关系:key-value
key为路径,value可能是function或component
1)后端路由:
value是function,处理客户端请求
服务器接收请求,根据请求路径找到匹配函数处理请求,返回响应数据
2)前端路由
value是component,展示页面内容
浏览器路径改变时,对应组件显示
3 使用
1)安装vue-router
npm i vue-router
2)应用插件
Vue.use(VueRouter)
3)编写router配置项
// 引入VueRouter
import VueRouter from "vue-router";
// 引入待路由的组件
import AboutVue from "../components/AboutVue.vue";
import HomeVue from "../components/HomeVue.vue";
// 创建并暴露一个路由器
export default new VueRouter({
routes: [
{
path: "/about",
component: AboutVue,
},
{
path: "/home",
component: HomeVue,
},
],
});
4)实现切换
<router-link active-class="active" to="/about">Aboout</router-link>
5)指定展示位置
<router-view></router-view>
4 注意
1)路由组件通常存放在pages文件夹,一般组件存放在components文件夹
2)通过切换,隐藏的路由组件,默认是销毁的,需要的时候再挂载
3)每个组件都有自己的$route属性,存储自己的路由信息
4)整个应用只有一个router,通过组件的$route属性获取到
1 配置路由规则,使用children配置项:
routes: [
// 一级路由
{
path: "/about",
component: AboutVue,
},
{
path: "/home",
component: HomeVue,
children: [
{
path: "news",
component: NewsVue,
},
{
path: "message",
component: MessageVue,
},
],
},
],
2 跳转(完整路径):
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
1 传递参数
字符串写法:
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{
m.title
}}</router-link>
对象写法:
<router-link
:to="{
path: '/home/message/detail',
query: {
id: m.id,
title: m.title,
},
}"
>
{{ m.title }}
</router-link>
2 接收参数:
$route.query.id
$route.query.title
1 作用:简化路由跳转
2 如何使用:
1)给路由命名:
export default new VueRouter({
routes: [
// 一级路由
{
name: "guanyu",
path: "/about",
component: AboutVue,
},
{
path: "/home",
component: HomeVue,
children: [
{
path: "news",
component: NewsVue,
},
{
path: "message",
component: MessageVue,
children: [
{
name: "xiangqing",
path: "detail",
component: DetailVue,
},
],
},
],
},
],
});
2)简化跳转:
简化前:
<router-link
:to="/demo/test/welcome">
跳转
</router-link>
简化后:
<router-link
:to="{name:'hello'}">
跳转
</router-link>
简化+传参:
<router-link
:to="{
name: 'xiangqing',
query: {
id: m.id,
title: m.title,
},
}"
>
{{ m.title }}
</router-link>
1 配置路由,声明接收params参数
{
path: "/home",
component: HomeVue,
children: [
{
path: "news",
component: NewsVue,
},
{
path: "message",
component: MessageVue,
children: [
{
path: "detail/:id/:title",
component: DetailVue,
},
],
},
],
},
2 传递参数
跳转携带params参数,to的字符串写法
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{
m.title
}}</router-link>
跳转携带params参数,to的对象写法
<router-link
:to="{
name: 'xiangqing',
params: {
id: m.id,
title: m.title,
},
}"
>
{{ m.title }}
</router-link>
注意:路由携带参数params时,若使用to的对象写法,不能使用path配置,必须使用name配置
3 接收参数
<ul>
<li>消息编号{{$route.params.id}}</li>
<li>消息标题{{$route.params.title}}</li>
</ul>
作用:让路由组件更方便的收到参数
{
name: "xiangqing",
path: "detail",
component: DetailVue,
// props第一种写法————对象
// 该对象所有key-value会以props形式DetailVue组件
// props:{a:1,b:'helloworld'}
// props第二种写法———布尔值
// 若为真,该路由组件收到所有params参数,以props形式传给DetailVue组件
// props: true,
// props第三种写法————函数
// 需要设置query传参
props($route) {
return { id: $routquery.id, title: $route.query.title;
},
// 或者解构赋值
// props({ query }) {
// return { id: query// },
// },
},
1 作用:控制路由跳转时操作浏览器历史记录的模式
2 浏览器历史记录有两种写入方式:
push模式————追加历史记录
前进后退。默认push模式
replace模式————替换当前历史记录
在router-link标签内追加 replace
或:replace='true'
1 作用:不借助<router-link>实现路由跳转,让路由跳转更灵活
2 编码:
this.$router.push({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.replace({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.forward(); // 前进
this.$router.back(); // 后退
this.$router.go(-1); // 可前可后
1 作用:让不显示的路由组件保持挂载,不被销毁
2 编码:
<keep-alive include="NewsVue">
<!--
此处填组件名
vue文件export default{}内部定义的name
-->
<router-view></router-view>
</keep-alive>
注意:
1)需要在保持不被销毁的父组件外侧使用keep-alive
2)若多个
<keep-alive :include=["NewsVue",'others']>
1 作用:路由组件独有的两个钩子,用于捕获路由组件的激活状态
2 具体名字:
1)activated路由组件被激活时触发
2)deactivated路由组件失活时触发
1 作用:对路由权限进行权限控制
2 分类:全局守卫、独享守卫、组件内守卫
3 全局守卫:
// 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
// if (to.path === "/home/news" || to.path === "/home/message") {
// 是否需要权限校验
if (to.meta.isAuth) {
if (localStorage.getItem("school") === "石大") {
next();
} else {
alert("学校名字不对");
}
} else {
next();
}
});
// 全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
console.log(to, from);
document.title = to.meta.title || "自定义系统";
});
4 独享守卫:
beforeEnter: (to, from, next) => {
console.log(from);
if (to.meta.isAuth) {
if (localStorage.getItem("school") === "石大") {
next();
} else {
alert("学校名字不对");
}
} else {
next();
}
},
5 组件内守卫
// 通过 路由规则 ,进入该组件时被调用
beforeRouteEnter(to, from, next) {
if (to.meta.isAuth) {
if (localStorage.getItem("school") === "石大") {
next();
} else {
alert("学校名字不对");
}
} else {
next();
}
},
// 通过 路由规则 ,离开该组件时被调用
// 若不设置next,不会离开该组件
beforeRouteLeave(to, from, next) {
next();
},
1 对于一个url说,什么是hash值————#及其后面的内容就是hash值
2 hash值不会包含在http请求中,及hash值不会带给服务器
3 hash模式
1)地址永远带#,不美观
2)若以后地址通过第三方手机app分享,若app校验严格,地址会被标注不合法
3)兼容性较好
4 history模式
1)地址干净、美观
2)兼容性相较hash略差
3)应用部署上线时需要后端人员支持,解决页面刷新服务端404的问题
1 移动端UI组件库
1) Vant https://youzan.github.io/vant
2) Cube UI https://didi.github.io/cube-uiu
3) Mint UI http://mint-ui.github.io
2 PC端常用UI组件库
1) ElementUI https://element.eleme.cn
2) IViewUI https://www.iviewui.com
3 ElementUI
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。