1. pinia是什么?
- 在
Vue3
中,可以使用传统的Vuex
来实现状态管理,也可以使用最新的pinia
来实现状态管理,我们来看看官网如何解释pinia
的:Pinia
是Vue
的存储库,它允许您跨组件/页面共享状态。- 实际上,
pinia
就是Vuex
的升级版,官网也说过,为了尊重原作者,所以取名pinia
,而没有取名Vuex
,所以大家可以直接将pinia
比作为Vue3
的Vuex
2. 为什么要使用pinia?
Vue2
和Vue3
都支持,这让我们同时使用Vue2
和Vue3
的小伙伴都能很快上手。pinia
中只有state
、getter
、action
,抛弃了Vuex
中的Mutation
,Vuex
中mutation
一直都不太受小伙伴们的待见,pinia
直接抛弃它了,这无疑减少了我们工作量。pinia
中action
支持同步和异步,Vuex
不支持Typescript
支持,毕竟我们Vue3
都推荐使用TS
来编写,这个时候使用pinia
就非常合适了Vuex
中如果数据过多,我们通常分模块来进行管理,稍显麻烦,而pinia
中每个store
都是独立的,互相不影响。1KB
左右。pinia
支持插件来扩展自身功能。3. pinna使用
pinna文档(opens new window)
我们这里搭建一个最新的Vue3 + TS + Vite
项目
npm create vite@latest my-vite-app --template vue-ts
pinia
基础使用yarn add pinia
// main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
const pinia = createPinia();const app = createApp(App);
app.use(pinia);
app.mount("#app");
2.1 创建store
//sbinsrc/store/user.ts
import { defineStore } from 'pinia'// 第一个参数是应用程序中 store 的唯一 id
export const useUsersStore = defineStore('users', {// 其它配置项
})
创建store
很简单,调用pinia
中的defineStore
函数即可,该函数接收两个参数:
name
:一个字符串,必传项,该store
的唯一id
。options
:一个对象,store
的配置项,比如配置store
内的数据,修改数据的方法等等。我们可以定义任意数量的store
,因为我们其实一个store
就是一个函数,这也是pinia
的好处之一,让我们的代码扁平化了,这和Vue3
的实现思想是一样的
2.2 使用store
2.3 添加state
export const useUsersStore = defineStore("users", {state: () => {return {name: "test",age: 20,sex: "男",};},
});
2.4 读取state
数据
![]()
姓名:{{ name }}
年龄:{{ age }}
性别:{{ sex }}
上段代码中我们直接通过store.age
等方式获取到了store
存储的值,但是大家有没有发现,这样比较繁琐,我们其实可以用解构的方式来获取值,使得代码更简洁一点
import { useUsersStore, storeToRefs } from "../src/store/user";
const store = useUsersStore();
const { name, age, sex } = storeToRefs(store); // storeToRefs获取的值是响应式的
2.5 修改state
数据
![]()
姓名:{{ name }}
年龄:{{ age }}
性别:{{ sex }}
2.6 重置state
state
数据,想要将它还原,这个时候该怎么做呢?就比如用户填写了一部分表单,突然想重置为最初始的状态。store
的$reset()
方法即可,继续使用我们的例子,添加一个重置按钮
// 重置store
const reset = () => {store.$reset();
};
当我们点击重置按钮时,store
中的数据会变为初始状态,页面也会更新
2.7 批量更改state
数据
如果我们一次性需要修改很多条数据的话,有更加简便的方法,使用store
的$patch
方法,修改app.vue
代码,添加一个批量更改数据的方法
// 批量修改数据
const patchStore = () => {store.$patch({name: "张三",age: 100,sex: "女",});
};
state
中有些字段无需更改,但是按照上段代码的写法,我们必须要将state中的所有字段例举出了。pinia
提供的$patch
方法还可以接收一个回调函数,它的用法有点像我们的数组循环回调函数了。store.$patch((state) => {state.items.push({ name: 'shoes', quantity: 1 })state.hasChanged = true
})
2.8 直接替换整个state
pinia
提供了方法让我们直接替换整个state
对象,使用store
的$state
方法
store.$state = { counter: 666, name: '张三' }
上段代码会将我们提前声明的state
替换为新的对象,可能这种场景用得比较少
getters
属性getters
是defineStore
参数配置项里面的另一个属性getter
想象成Vue
中的计算属性,它的作用就是返回一个新的结果,既然它和Vue
中的计算属性类似,那么它肯定也是会被缓存的,就和computed
一样3.1 添加getter
export const useUsersStore = defineStore("users", {state: () => {return {name: "test",age: 10,sex: "男",};},getters: {getAddAge: (state) => {return state.age + 100;},},
})
上段代码中我们在配置项参数中添加了getter
属性,该属性对象中定义了一个getAddAge
方法,该方法会默认接收一个state
参数,也就是state
对象,然后该方法返回的是一个新的数据
3.2 使用getter
新年龄:{{ store.getAddAge }}
上段代码中我们直接在标签上使用了store.gettAddAge
方法,这样可以保证响应式,其实我们state
中的name
等属性也可以以此种方式直接在标签上使用,也可以保持响应式
3.3 getter
中调用其它getter
export const useUsersStore = defineStore("users", {state: () => {return {name: "test",age: 20,sex: "男",};},getters: {getAddAge: (state) => {return state.age + 100;},getNameAndAge(): string {return this.name + this.getAddAge; // 调用其它getter},},
});
3.3 getter
传参
export const useUsersStore = defineStore("users", {state: () => {return {name: "test",age: 20,sex: "男",};},getters: {getAddAge: (state) => {return (num: number) => state.age + num;},getNameAndAge(): string {return this.name + this.getAddAge; // 调用其它getter},},
});
新年龄:{{ store.getAddAge(1100) }}
actions
属性state
和getter
s属性都主要是数据层面的,并没有具体的业务逻辑代码,它们两个就和我们组件代码中的data
数据和computed
计算属性一样。actions
属性里面,该属性就和我们组件代码中的methods
相似,用来放置一些处理业务逻辑的方法。actions
属性值同样是一个对象,该对象里面也是存储的各种各样的方法,包括同步方法和异步方法4.1 添加actions
export const useUsersStore = defineStore("users", {state: () => {return {name: "test",age: 20,sex: "男",};},getters: {getAddAge: (state) => {return (num: number) => state.age + num;},getNameAndAge(): string {return this.name + this.getAddAge; // 调用其它getter},},actions: {// 在实际场景中,该方法可以是任何逻辑,比如发送请求、存储token等等。大家把actions方法当作一个普通的方法即可,特殊之处在于该方法内部的this指向的是当前storesaveName(name: string) {this.name = name;},},
});
4.2 使用actions
使用actions
中的方法也非常简单,比如我们在App.vue
中想要调用该方法
const saveName = () => {store.saveName("poetries");
};
总结
pinia
的知识点很少,如果你有Vuex基础,那么学起来更是易如反掌
pinia无非就是以下3个大点:
state
getters
actions
computed
Computed
本质是一个具备缓存的watcher
,依赖的属性发生变化就会更新视图。 适用于计算比较消耗性能的计算场景。当表达式过于复杂时,在模板中放入过多逻辑会让模板难以维护,可以将复杂的逻辑放入计算属性中处理
{{fullName}}
export default {data(){return {firstName: 'zhang',lastName: 'san',}},computed:{fullName: function(){return this.firstName + ' ' + this.lastName}}
}
watch
用于观察和监听页面上的vue实例,如果要在数据变化的同时进行异步操作或者是比较大的开销,那么watch
为最佳选择
Watch
没有缓存性,更多的是观察的作用,可以监听某些数据执行回调。当我们需要深度监听对象中的属性时,可以打开deep:true
选项,这样便会对对象中的每一项进行监听。这样会带来性能问题,优化的话可以使用字符串形式监听,如果没有写到组件中,不要忘记使用unWatch
手动注销
{{fullName}}
export default {data(){return {firstName: 'zhang',lastName: 'san',fullName: 'zhang san'}},watch:{firstName(val) {this.fullName = val + ' ' + this.lastName},lastName(val) {this.fullName = this.firstName + ' ' + val}}
}
computed:
computed
是计算属性,也就是计算值,它更多用于计算值的场景computed
具有缓存性,computed
的值在getter
执行后是会缓存的,只有在它依赖的属性值改变之后,下一次获取computed
的值时才会重新调用对应的getter
来计算computed
适用于计算比较消耗性能的计算场景watch:
props
$emit
或者本组件的值,当数据变化时来执行回调进行后续操作小结:
computed
和watch
都是基于watcher
来实现的computed
属性是具备缓存的,依赖的值不发生变化,对其取值时计算属性方法不会重新执行watch
是监控值的变化,当值发生变化时调用其对应的回调函数computed
watch
来观察这个数据变化回答范例
思路分析
computed
, watch
两者定义,列举使用上的差异vue3
变化computed
特点:具有响应式的返回值
const count = ref(1)
const plusOne = computed(() => count.value + 1)
watch
特点:侦测变化,执行回调
const state = reactive({ count: 0 })
watch(() => state.count,(count, prevCount) => {/* ... */}
)
回答范例
computed
和methods
的差异是它具备缓存性,如果依赖项不变时不会重新计算。侦听器可以侦测某个响应式数据的变化并执行副作用,常见用法是传递一个函数,执行副作用,watch没有返回值,但可以执行异步操作等复杂逻辑watch
可以传递对象,设置deep
、immediate
等选项vue3
中watch
选项发生了一些变化,例如不再能侦测一个点操作符之外的字符串形式的表达式; reactivity API
中新出现了watch
、watchEffect
可以完全替代目前的watch
选项,且功能更加强大基本使用
// src/core/observer:45;// 渲染watcher / computed watcher / watch
const vm = new Vue({el: '#app',data: {firstname:'张',lastname:'三'},computed:{ // watcher => firstname lastname// computed 只有取值时才执行// Object.defineProperty .getfullName(){ // firstName lastName 会收集fullName计算属性return this.firstname + this.lastname}},watch:{firstname(newVal,oldVal){console.log(newVal)}}
});setTimeout(() => {debugger;vm.firstname = '赵'
}, 1000);
相关源码
// 初始化state
function initState (vm: Component) {vm._watchers = []const opts = vm.$optionsif (opts.props) initProps(vm, opts.props)if (opts.methods) initMethods(vm, opts.methods)if (opts.data) {initData(vm)} else {observe(vm._data = {}, true /* asRootData */)}// 初始化计算属性if (opts.computed) initComputed(vm, opts.computed) // 初始化watchif (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch)}
}// 计算属性取值函数
function createComputedGetter (key) {return function computedGetter () {const watcher = this._computedWatchers && this._computedWatchers[key]if (watcher) {if (watcher.dirty) { // 如果值依赖的值发生变化,就会进行重新求值watcher.evaluate(); // this.firstname lastname}if (Dep.target) { // 让计算属性所依赖的属性 收集渲染watcherwatcher.depend()}return watcher.value}}
}// watch的实现
Vue.prototype.$watch = function (expOrFn: string | Function,cb: any,options?: Object): Function {const vm: Component = thisdebugger;if (isPlainObject(cb)) {return createWatcher(vm, expOrFn, cb, options)}options = options || {}options.user = trueconst watcher = new Watcher(vm, expOrFn, cb, options) // 创建watcher,数据更新调用cbif (options.immediate) {try {cb.call(vm, watcher.value)} catch (error) {handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)}}return function unwatchFn () {watcher.teardown()}
}
事件修饰符
v-model 的修饰符
键盘事件的修饰符
系统修饰键
鼠标按钮修饰符
Vue 的编译过程就是将 template 转化为 render 函数的过程 分为以下三步
第一步是将 模板字符串 转换成 element ASTs(解析器)
第二步是对 AST 进行静态节点标记,主要用来做虚拟DOM的渲染优化(优化器)
第三步是 使用 element ASTs 生成 render 函数代码字符串(代码生成器)
可以。v-model 实际上是一个语法糖,如:
实际上相当于:
用在自定义组件上也是同理:
相当于:
显然,custom-input 与父组件的交互如下:
searchText
变量传入custom-input 组件,使用的 prop 名为value
;input
的事件,父组件将接收到的值赋值给searchText
;所以,custom-input 组件的实现应该类似于这样:
Vue.component('custom-input', {props: ['value'],template: ` `
})
keep-alive 可以实现组件的缓存,当组件切换时不会对当前组件进行卸载。常用的2个属性
include/exclude ,2个生命周期
activated ,
deactivated
参考 前端进阶面试题详细解答
这个 API 很少用到,作用是扩展组件生成一个构造器,通常会与 $mount
一起使用。
// 创建组件构造器
let Component = Vue.extend({ template: "test" });
// 挂载到 #app 上new Component().$mount('#app')
// 除了上面的方式,还可以用来扩展已有的组件
let SuperComponent = Vue.extend(Component);
new SuperComponent({created() {console.log(1);},
});
new SuperComponent().$mount("#app");
mutation
是同步更新, $watch
严格模式下会报错 action
是异步操作,可以获取数据后调用 mutation
提交最终数据既然是要保持页面的状态(其实也就是组件的状态),那么会出现以下两种情况:
那么可以按照这两种情况分别得到以下方法:
组件会被卸载:
(1)将状态存储在LocalStorage / SessionStorage
只需要在组件即将被销毁的生命周期 componentWillUnmount
(react)中在 LocalStorage / SessionStorage 中把当前组件的 state 通过 JSON.stringify() 储存下来就可以了。在这里面需要注意的是组件更新状态的时机。
比如从 B 组件跳转到 A 组件的时候,A 组件需要更新自身的状态。但是如果从别的组件跳转到 B 组件的时候,实际上是希望 B 组件重新渲染的,也就是不要从 Storage 中读取信息。所以需要在 Storage 中的状态加入一个 flag 属性,用来控制 A 组件是否读取 Storage 中的状态。
优点:
缺点:
(2)路由传值
通过 react-router 的 Link 组件的 prop —— to 可以实现路由间传递参数的效果。
在这里需要用到 state 参数,在 B 组件中通过 history.location.state 就可以拿到 state 值,保存它。返回 A 组件时再次携带 state 达到路由状态保持的效果。
优点:
缺点:
组件不会被卸载:
(1)单页面渲染
要切换的组件作为子组件全屏渲染,父组件中正常储存页面状态。
优点:
缺点:
除此之外,在Vue中,还可以是用keep-alive来缓存页面,当组件在keep-alive内被切换时组件的activated、deactivated这两个生命周期钩子函数会被执行
被包裹在keep-alive中的组件的状态将会被保留:
router.js
{path: '/',name: 'xxx',component: ()=>import('../src/views/xxx.vue'),meta:{keepAlive: true // 需要被缓存}
},
1. 分析
首先找到vue
的构造函数
源码位置:src\core\instance\index.js
function Vue (options) {if (process.env.NODE_ENV !== 'production' &&!(this instanceof Vue)) {warn('Vue is a constructor and should be called with the `new` keyword')}this._init(options)
}
options
是用户传递过来的配置项,如data、methods
等常用的方法
vue
构建函数调用_init
方法,但我们发现本文件中并没有此方法,但仔细可以看到文件下方定定义了很多初始化方法
initMixin(Vue); // 定义 _init
stateMixin(Vue); // 定义 $set $get $delete $watch 等
eventsMixin(Vue); // 定义事件 $on $once $off $emit
lifecycleMixin(Vue);// 定义 _update $forceUpdate $destroy
renderMixin(Vue); // 定义 _render 返回虚拟dom
首先可以看initMixin
方法,发现该方法在Vue
原型上定义了_init
方法
源码位置:src\core\instance\init.js
Vue.prototype._init = function (options?: Object) {const vm: Component = this// a uidvm._uid = uid++let startTag, endTag/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {startTag = `vue-perf-start:${vm._uid}`endTag = `vue-perf-end:${vm._uid}`mark(startTag)}// a flag to avoid this being observedvm._isVue = true// merge options// 合并属性,判断初始化的是否是组件,这里合并主要是 mixins 或 extends 的方法if (options && options._isComponent) {// optimize internal component instantiation// since dynamic options merging is pretty slow, and none of the// internal component options needs special treatment.initInternalComponent(vm, options)} else { // 合并vue属性vm.$options = mergeOptions(resolveConstructorOptions(vm.constructor),options || {},vm)}/* istanbul ignore else */if (process.env.NODE_ENV !== 'production') {// 初始化proxy拦截器initProxy(vm)} else {vm._renderProxy = vm}// expose real selfvm._self = vm// 初始化组件生命周期标志位initLifecycle(vm)// 初始化组件事件侦听initEvents(vm)// 初始化渲染方法initRender(vm)callHook(vm, 'beforeCreate')// 初始化依赖注入内容,在初始化data、props之前initInjections(vm) // resolve injections before data/props// 初始化props/data/method/watch/methodsinitState(vm)initProvide(vm) // resolve provide after data/propscallHook(vm, 'created')/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {vm._name = formatComponentName(vm, false)mark(endTag)measure(`vue ${vm._name} init`, startTag, endTag)}// 挂载元素if (vm.$options.el) {vm.$mount(vm.$options.el)}}
仔细阅读上面的代码,我们得到以下结论:
beforeCreate
之前,数据初始化并未完成,像data
、props
这些属性无法访问到created
的时候,数据已经初始化完成,能够访问data
、props
这些属性,但这时候并未完成dom
的挂载,因此无法访问到dom
元素vm.$mount
方法initState
方法是完成props/data/method/watch/methods
的初始化
源码位置:src\core\instance\state.js
export function initState (vm: Component) {// 初始化组件的watcher列表vm._watchers = []const opts = vm.$options// 初始化propsif (opts.props) initProps(vm, opts.props)// 初始化methods方法if (opts.methods) initMethods(vm, opts.methods)if (opts.data) {// 初始化data initData(vm)} else {observe(vm._data = {}, true /* asRootData */)}if (opts.computed) initComputed(vm, opts.computed)if (opts.watch && opts.watch !== nativeWatch) {initWatch(vm, opts.watch)}
}
我们和这里主要看初始化data
的方法为initData
,它与initState
在同一文件上
function initData (vm: Component) {let data = vm.$options.data// 获取到组件上的datadata = vm._data = typeof data === 'function'? getData(data, vm): data || {}if (!isPlainObject(data)) {data = {}process.env.NODE_ENV !== 'production' && warn('data functions should return an object:\n' +'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',vm)}// proxy data on instanceconst keys = Object.keys(data)const props = vm.$options.propsconst methods = vm.$options.methodslet i = keys.lengthwhile (i--) {const key = keys[i]if (process.env.NODE_ENV !== 'production') {// 属性名不能与方法名重复if (methods && hasOwn(methods, key)) {warn(`Method "${key}" has already been defined as a data property.`,vm)}}// 属性名不能与state名称重复if (props && hasOwn(props, key)) {process.env.NODE_ENV !== 'production' && warn(`The data property "${key}" is already declared as a prop. ` +`Use prop default value instead.`,vm)} else if (!isReserved(key)) { // 验证key值的合法性// 将_data中的数据挂载到组件vm上,这样就可以通过this.xxx访问到组件上的数据proxy(vm, `_data`, key)}}// observe data// 响应式监听data是数据的变化observe(data, true /* asRootData */)
}
仔细阅读上面的代码,我们可以得到以下结论:
props
、methods
、data
data
定义的时候可选择函数形式或者对象形式(组件只能为函数形式)关于数据响应式在这就不展开详细说明
上文提到挂载方法是调用vm.$mount
方法
源码位置:
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {// 获取或查询元素el = el && query(el)/* istanbul ignore if */// vue 不允许直接挂载到body或页面文档上if (el === document.body || el === document.documentElement) {process.env.NODE_ENV !== 'production' && warn(`Do not mount Vue to or - mount to normal elements instead.`)return this}const options = this.$options// resolve template/el and convert to render functionif (!options.render) {let template = options.template// 存在template模板,解析vue模板文件if (template) {if (typeof template === 'string') {if (template.charAt(0) === '#') {template = idToTemplate(template)/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && !template) {warn(`Template element not found or is empty: ${options.template}`,this)}}} else if (template.nodeType) {template = template.innerHTML} else {if (process.env.NODE_ENV !== 'production') {warn('invalid template option:' + template, this)}return this}} else if (el) {// 通过选择器获取元素内容template = getOuterHTML(el)}if (template) {/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {mark('compile')}/*** 1.将temmplate解析ast tree* 2.将ast tree转换成render语法字符串* 3.生成render方法*/const { render, staticRenderFns } = compileToFunctions(template, {outputSourceRange: process.env.NODE_ENV !== 'production',shouldDecodeNewlines,shouldDecodeNewlinesForHref,delimiters: options.delimiters,comments: options.comments}, this)options.render = renderoptions.staticRenderFns = staticRenderFns/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {mark('compile end')measure(`vue ${this._name} compile`, 'compile', 'compile end')}}}return mount.call(this, el, hydrating)
}
阅读上面代码,我们能得到以下结论:
body
或者html
上template/render
或者直接使用template
、el
表示元素选择器render
函数,调用compileToFunctions
,会将template
解析成render
函数对template
的解析步骤大致分为以下几步:
html
文档片段解析成ast
描述符ast
描述符解析成字符串render
函数生成render
函数,挂载到vm
上后,会再次调用mount
方法
源码位置:src\platforms\web\runtime\index.js
// public mount method
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {el = el && inBrowser ? query(el) : undefined// 渲染组件return mountComponent(this, el, hydrating)
}
调用mountComponent
渲染组件
export function mountComponent (vm: Component,el: ?Element,hydrating?: boolean
): Component {vm.$el = el// 如果没有获取解析的render函数,则会抛出警告// render是解析模板文件生成的if (!vm.$options.render) {vm.$options.render = createEmptyVNodeif (process.env.NODE_ENV !== 'production') {/* istanbul ignore if */if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||vm.$options.el || el) {warn('You are using the runtime-only build of Vue where the template ' +'compiler is not available. Either pre-compile the templates into ' +'render functions, or use the compiler-included build.',vm)} else {// 没有获取到vue的模板文件warn('Failed to mount component: template or render function not defined.',vm)}}}// 执行beforeMount钩子callHook(vm, 'beforeMount')let updateComponent/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {updateComponent = () => {const name = vm._nameconst id = vm._uidconst startTag = `vue-perf-start:${id}`const endTag = `vue-perf-end:${id}`mark(startTag)const vnode = vm._render()mark(endTag)measure(`vue ${name} render`, startTag, endTag)mark(startTag)vm._update(vnode, hydrating)mark(endTag)measure(`vue ${name} patch`, startTag, endTag)}} else {// 定义更新函数updateComponent = () => {// 实际调⽤是在lifeCycleMixin中定义的_update和renderMixin中定义的_rendervm._update(vm._render(), hydrating)}}// we set this to vm._watcher inside the watcher's constructor// since the watcher's initial patch may call $forceUpdate (e.g. inside child// component's mounted hook), which relies on vm._watcher being already defined// 监听当前组件状态,当有数据变化时,更新组件new Watcher(vm, updateComponent, noop, {before () {if (vm._isMounted && !vm._isDestroyed) {// 数据更新引发的组件更新callHook(vm, 'beforeUpdate')}}}, true /* isRenderWatcher */)hydrating = false// manually mounted instance, call mounted on self// mounted is called for render-created child components in its inserted hookif (vm.$vnode == null) {vm._isMounted = truecallHook(vm, 'mounted')}return vm
}
阅读上面代码,我们得到以下结论:
boforeCreate
钩子updateComponent
渲染页面视图的方法beforeUpdate
生命钩子updateComponent
方法主要执行在vue
初始化时声明的render
,update
方法
render的作用主要是生成
vnode
源码位置:src\core\instance\render.js
// 定义vue 原型上的render方法
Vue.prototype._render = function (): VNode {const vm: Component = this// render函数来自于组件的optionconst { render, _parentVnode } = vm.$optionsif (_parentVnode) {vm.$scopedSlots = normalizeScopedSlots(_parentVnode.data.scopedSlots,vm.$slots,vm.$scopedSlots)}// set parent vnode. this allows render functions to have access// to the data on the placeholder node.vm.$vnode = _parentVnode// render selflet vnodetry {// There's no need to maintain a stack because all render fns are called// separately from one another. Nested component's render fns are called// when parent component is patched.currentRenderingInstance = vm// 调用render方法,自己的独特的render方法, 传入createElement参数,生成vNodevnode = render.call(vm._renderProxy, vm.$createElement)} catch (e) {handleError(e, vm, `render`)// return error render result,// or previous vnode to prevent render error causing blank component/* istanbul ignore else */if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {try {vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)} catch (e) {handleError(e, vm, `renderError`)vnode = vm._vnode}} else {vnode = vm._vnode}} finally {currentRenderingInstance = null}// if the returned array contains only a single node, allow itif (Array.isArray(vnode) && vnode.length === 1) {vnode = vnode[0]}// return empty vnode in case the render function errored outif (!(vnode instanceof VNode)) {if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {warn('Multiple root nodes returned from render function. Render function ' +'should return a single root node.',vm)}vnode = createEmptyVNode()}// set parentvnode.parent = _parentVnodereturn vnode
}
_update
主要功能是调用patch
,将vnode
转换为真实DOM
,并且更新到页面中
源码位置:src\core\instance\lifecycle.js
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {const vm: Component = thisconst prevEl = vm.$elconst prevVnode = vm._vnode// 设置当前激活的作用域const restoreActiveInstance = setActiveInstance(vm)vm._vnode = vnode// Vue.prototype.__patch__ is injected in entry points// based on the rendering backend used.if (!prevVnode) {// initial render// 执行具体的挂载逻辑vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)} else {// updatesvm.$el = vm.__patch__(prevVnode, vnode)}restoreActiveInstance()// update __vue__ referenceif (prevEl) {prevEl.__vue__ = null}if (vm.$el) {vm.$el.__vue__ = vm}// if parent is an HOC, update its $el as wellif (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {vm.$parent.$el = vm.$el}// updated hook is called by the scheduler to ensure that children are// updated in a parent's updated hook.}
2. 结论
new Vue
的时候调用会调用_init
方法 $set
、$get
、$delete
、$watch
等方法$on
、$off
、$emit
、$off
等事件_update
、$forceUpdate
、$destroy
生命周期$mount
进行页面的挂载mountComponent
方法updateComponent
更新函数render
生成虚拟DOM
_update
将虚拟DOM
生成真实DOM
结构,并且渲染到页面中不会立即同步执行重新渲染。Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。Vue 在更新 DOM 时是异步执行的。只要侦听到数据变化, Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。
如果同一个watcher被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。然后,在下一个的事件循环tick中,Vue 刷新队列并执行实际(已去重的)工作。
在 Vue2 中, 0bject.defineProperty 会改变原始数据,而 Proxy 是创建对象的虚拟表示,并提供 set 、get 和 deleteProperty 等处理器,这些处理器可在访问或修改原始对象上的属性时进行拦截,有以下特点∶
Vue.$set
或 Vue.$delete
触发响应式。Proxy 实现的响应式原理与 Vue2的实现原理相同,实现方式大同小异∶
思路分析:
首先思考vue
路由要解决的问题:用户点击跳转链接内容切换,页面不刷新。
hash
或者history api
实现url
跳转页面不刷新hashchange
事件或者popstate
事件处理跳转hash
值或者state
值从routes
表中匹配对应component
并渲染回答范例:
一个SPA
应用的路由需要解决的问题是 页面跳转内容改变同时不刷新 ,同时路由还需要以插件形式存在,所以:
createRouter
函数,返回路由器实例,实例内部做几件事hash
或者popstate
事件path
匹配对应路由router
定义成一个Vue
插件,即实现install
方法,内部做两件事router-link
和router-view
,分别实现页面跳转和内容显示$route
和$router
,组件内可以访问当前路由和路由器实例(1)编码阶段
(2)SEO优化
(3)打包优化
(4)用户体验
SPA
( single-page application )仅在Web
页面初始化时加载相应的HTML
、JavaScript
和CSS
。一旦页面加载完成,SPA
不会因为用户的操作而进行页面的重新加载或跳转;取而代之的是利用路由机制实现HTML
内容的变换,UI
与用户的交互,避免页面的重新加载
优点:
SPA
相对对服务器压力小;缺点:
Web
应用功能及显示效果,需要在加载页面的时候将 JavaScript
、CSS
统一加载,部分页面按需加载;SEO
难度较大:由于所有的内容都在一个页面中动态替换显示,所以在 SEO
上其有着天然的弱势单页应用与多页应用的区别
单页面应用(SPA) | 多页面应用(MPA) | |
---|---|---|
组成 | 一个主页面和多个页面片段 | 多个主页面 |
刷新方式 | 局部刷新 | 整页刷新 |
url 模式 | 哈希模式 | 历史模式 |
SEO 搜索引擎优化 | 难实现,可使用SSR方式改善 | 容易实现 |
数据传递 | 容易 | 通过url 、cookie 、localStorage 等传递 |
页面切换 | 速度快,用户体验良好 | 切换加载资源,速度慢,用户体验差 |
维护成本 | 相对容易 | 相对复杂 |
实现一个SPA
hash
变化驱动界面变化pushsate
记录浏览器的历史,驱动界面发送变化url
中的hash
来进行路由跳转// 定义 Router
class Router { constructor () { this.routes = {}; // 存放路由path及callback this.currentUrl = ''; // 监听路由change调用相对应的路由回调 window.addEventListener('load', this.refresh, false); window.addEventListener('hashchange', this.refresh, false); } route(path, callback){ this.routes[path] = callback; } push(path) { this.routes[path] && this.routes[path]() }
} // 使用 router
window.miniRouter = new Router();
miniRouter.route('/', () => console.log('page1'))
miniRouter.route('/page2', () => console.log('page2')) miniRouter.push('/') // page1
miniRouter.push('/page2') // page2
history
模式核心借用 HTML5 history api
,api
提供了丰富的 router
相关属性先了解一个几个相关的apihistory.pushState
浏览器历史纪录添加记录history.replaceState
修改浏览器历史纪录中当前纪录history.popState
当 history
发生变化时触发// 定义 Router
class Router { constructor () { this.routes = {}; this.listerPopState() } init(path) { history.replaceState({path: path}, null, path); this.routes[path] && this.routes[path](); } route(path, callback){ this.routes[path] = callback; } push(path) { history.pushState({path: path}, null, path); this.routes[path] && this.routes[path](); } listerPopState () { window.addEventListener('popstate' , e => { const path = e.state && e.state.path; this.routers[path] && this.routers[path]() }) }
} // 使用 Router window.miniRouter = new Router();
miniRouter.route('/', ()=> console.log('page1'))
miniRouter.route('/page2', ()=> console.log('page2')) // 跳转
miniRouter.push('/page2') // page2
题外话:如何给SPA做SEO
将组件或页面通过服务器生成html
,再返回给浏览器,如nuxt.js
目前主流的静态化主要有两种:
一种是通过程序将动态页面抓取并保存为静态页面,这样的页面的实际存在于服务器的硬盘中
另外一种是通过WEB服务器的 URL Rewrite
的方式,它的原理是通过web服务器内部模块按一定规则将外部的URL请求转化为内部的文件地址,一句话来说就是把外部请求的静态地址转化为实际的动态页面地址,而静态页面实际是不存在的。这两种方法都达到了实现URL静态化的效果
Phantomjs
针对爬虫处理原理是通过Nginx
配置,判断访问来源是否为爬虫,如果是则搜索引擎的爬虫请求会转发到一个node server
,再通过PhantomJS
来解析完整的HTML
,返回给爬虫。下面是大致流程图
这是一个实践知识点,组件化开发过程中有个单项数据流原则
,不在子组件中修改父组件是个常识问题
思路
回答范例
prop
都使得其父子之间形成了一个单向下行绑定:父级 prop
的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。另外,每次父级组件发生变更时,子组件中所有的 prop
都将会刷新为最新的值。这意味着你不应该在一个子组件内部改变 prop
。如果你这样做了,Vue
会在浏览器控制台中发出警告const props = defineProps(['foo'])
// ❌ 下面行为会被警告, props是只读的!
props.foo = 'bar'
这个 prop 用来传递一个初始值;这个子组件接下来希望将其作为一个本地的 prop 数据来使用。 在这种情况下,最好定义一个本地的 data
,并将这个 prop
用作其初始值:
const props = defineProps(['initialCounter'])
const counter = ref(props.initialCounter)
这个 prop 以一种原始的值传入且需要进行转换。 在这种情况下,最好使用这个 prop
的值来定义一个计算属性:
const props = defineProps(['size'])
// prop变化,计算属性自动更新
const normalizedSize = computed(() => props.size.trim().toLowerCase())
emit
一个事件让父组件去做这个变更。注意虽然我们不能直接修改一个传入的对象或者数组类型的prop
,但是我们还是能够直接改内嵌的对象或属性1. hash
模式
早期的前端路由的实现就是基于 location.hash
来实现的。其实现原理很简单,location.hash
的值就是 URL
中 #
后面的内容。比如下面这个网站,它的 location.hash
的值为 '#search'
https://interview2.poetries.top#search
hash 路由模式的实现主要是基于下面几个特性
URL
中 hash
值只是客户端的一种状态,也就是说当向服务器端发出请求时,hash
部分不会被发送;hash
值的改变,都会在浏览器的访问历史中增加一个记录。因此我们能通过浏览器的回退、前进按钮控制 hash
的切换;a
标签,并设置 href
属性,当用户点击这个标签后,URL
的 hash
值会发生改变;或者使用 JavaScript
来对 loaction.hash
进行赋值,改变 URL
的 hash
值;hashchange
事件来监听 hash
值的变化,从而对页面进行跳转(渲染)window.addEventListener("hashchange", funcRef, false);
每一次改变 hash
(window.location.hash
),都会在浏览器的访问历史中增加一个记录利用 hash
的以上特点,就可以来实现前端路由“更新视图但不重新请求页面”的功能了
特点 :兼容性好但是不美观
2. history
模式
history
采用HTML5
的新特性;且提供了两个新方法: pushState()
, replaceState()
可以对浏览器历史记录栈进行修改,以及popState
事件的监听到状态变更
window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);
这两个方法有个共同的特点:当调用他们修改浏览器历史记录栈后,虽然当前 URL
改变了,但浏览器不会刷新页面,这就为单页应用前端路由“更新视图但不重新请求页面”提供了基础。
history 路由模式的实现主要基于存在下面几个特性:
pushState
和 repalceState
两个 API
来操作实现 URL
的变化 ;popstate
事件来监听 url
的变化,从而对页面进行跳转(渲染);history.pushState()
或 history.replaceState()
不会触发 popstate
事件,这时我们需要手动触发页面跳转(渲染)。特点 :虽然美观,但是刷新会出现 404
需要后端进行配置