赞
踩
目录
- const data = {
- name: 'zhangsan',
- age:21,
- info: {
- address: 'BeiJing'
- },
- num: [1,2,3]
- }
-
-
- // 重新定义数组的原型,不建议直接重写数组的方法,否则就会污染全局的原型方法
- let oldArrayProperty = Array.prototype;
- var arrProto = Object.create(oldArrayProperty);
- ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(methodName => {
- arrProto[methodName] = function(){
- updateView ();
- oldArrayProperty[methodName].call(this, ...arguments);
- }
- })
-
-
-
- function updateView(){
- console.log('update view');
- }
-
- function observer(target){
- if (typeof target !== 'object' || target === null){
- return target;
- }
-
- if (Array.isArray(target)){
- target.__proto__ = arrProto;
- }
-
- for (let key in target){
- defineReactive(target, key, target[key])
- }
- }
-
- function defineReactive(target, key, value){
- // 深度监听
- observer(value);
-
- Object.defineProperty(target, key, {
- get(){
- return value
- },
- set(newValue){
- // 设置的新值可能还是一个object
- observer(newValue);
- if (newValue !== value){
- value = newValue
- updateView();
- }
- }
- })
- }
-
- // 执行observer必须等数组方法重写后进行监听
- observer(data);
-
- data.name = 'lisi';
- data.age = 20;
- data.info.address = 'ShangHai';
- data.num.push(4)
activated和deactivated会在keep-alive树内所有嵌套的组件中触发
如:B页面是缓存页面
当A页面跳到B页面时,B页面的生命周期:activated(可在此时更新数据)
B页面跳出时,触发deactivated
B页面自身刷新时,会触发created-mouted-activated
router.meta 属性来实现
- export default {
- name: 'hello',
- //keep-alive钩子函数:组件被激活时调用
- activated() {
- console.log('首页被激活');
- },
- //keep-alive钩子函数:组件消失,被缓存时调用
- deactivated() {
- console.log('首页被缓存');
- },
- beforeRouteLeave(to, from, next) {
- //设置下一个路由的meta(即首页)
- to.meta.keepAlive = true; // 让首页缓存,即不刷新
- next();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。