1. bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。2. inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已**入文档中)。3. update:被绑定于元素所在的模板更新时调用,而无论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新。4. componentUpdated:被绑定元素所在模板完成一次更新周期时调用。5. unbind:只调用一次,指令与元素解绑时调用。
讯享网
讯享网class Store { constructor(options) { this.state = reactive(options.state) this.options = options } commit(type, payload) { this.options.mutations[type].call(this, this.state, payload) }}
/ * 1 实现插件,挂载\(store * 2 实现store */let Vue;class Store { constructor(options) { // state响应式处理 // 外部访问: this.\)store.state.* // 第一种写法 // this.state = new Vue({ // data: options.state // })// 第二种写法:防止外界直接接触内部vue实例,防止外部强行变更 this._vm = new Vue({ data: { $$state: options.state } })this._mutations = options.mutations this._actions = options.actions this.getters = {} options.getters && this.handleGetters(options.getters)this.commit = this.commit.bind(this) this.dispatch = this.dispatch.bind(this) }get state () { return this._vm._data.$$state }set state (val) { return new Error(‘Please use replaceState to reset state’) }handleGetters (getters) { Object.keys(getters).map(key => { Object.defineProperty(this.getters, key, { get: () => getterskey }) }) }commit (type, payload) { let entry = this._mutations[type] if (!entry) { return new Error(${type} is not defined) }entry(this.state, payload) }dispatch (type, payload) { let entry = this._actions[type] if (!entry) { return new Error(${type} is not defined) }entry(this, payload) }}const install = (_Vue) => { Vue = _VueVue.mixin({ beforeCreate () { if (this.\(options.store) { Vue.prototype.\)store = this.\(options.store } }, })}export default { Store, install }</pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 77, 77); line-height: 26px; overflow: auto hidden;">验证方式</p><pre style='box-sizing: border-box; font-family: "Source Code Pro", "DejaVu Sans Mono", "Ubuntu Mono", "Anonymous Pro", "Droid Sans Mono", Menlo, Monaco, Consolas, Inconsolata, Courier, monospace, "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 14px; margin-top: 1.2em; margin-bottom: 24px; line-height: 22px; color: rgb(0, 0, 0);'>import Vue from 'vue'import Vuex from 'https://maimai.cn/article/vuex'// this.\)storeVue.use(Vuex)export default new Vuex.Store({ state: { counter: 0 }, mutations: { // state从哪里来的 add (state) { state.counter++ } }, getters: { doubleCounter (state) { return state.counter * 2 } }, actions: { add ({ commit }) { setTimeout(() => { commit(‘add’) }, 1000) } }, modules: { }})
讯享网父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount- >子mounted->父mounted
父beforeUpdate->子beforeUpdate->子updated->父updated
讯享网父 beforeUpdate -> 父 updated
父beforeDestroy->子beforeDestroy->子destroyed->父destroyed
答案
讯享网<template><div> 请输入firstName: <input type=“text” v-model=“firstName”></div><div> 请输入lastName: <input type=“text” v-model=“lastName”></div><div> 请输入obj.text: <input type=“text” v-model=“obj.text”></div> <div> 【obj.text】 {{obj.text}} </div></template><script>import {ref, reactive, watch, watchEffect} from ’vue’export default { name: ”HelloWorld”, props: { msg: String, }, setup(props,content){ let firstName = ref(“) let lastName = ref(”) let obj= reactive({ text:‘hello’ }) watchEffect(()=>{ console.log(‘触发了watchEffect’); console.log(组合后的名称为:${firstName.value}${lastName.value}) }) return{ obj, firstName, lastName } }};</script>
watchEffect(()=>{ console.log(‘触发了watchEffect’); // 这里我们不使用firstName.value/lastName.value ,相当于是监控整个ref,对应第四点上面的结论 console.log(组合后的名称为:${firstName}${lastName})})
讯享网watchEffect(()=>{ console.log(‘触发了watchEffect’); console.log(obj);})
let obj = reactive({ text:‘hello’})watchEffect(()=>{ console.log(‘触发了watchEffect’); console.log(obj.text);})
讯享网let obj= reactive({ text:‘hello’})// watch是惰性执行, 默认初始化之后不会执行,只有值有变化才会触发,可通过配置参数实现默认执行watch(obj, (newValue, oldValue) => { // 回调函数 console.log(‘触发监控更新了new’, newValue); console.log(‘触发监控更新了old’, oldValue);},{ // 配置immediate参数,立即执行,以及深层次监听 immediate: true, deep: true})
const count = ref(0)watchEffect(() => console.log(count.value))// -> logs 0count.value++// -> logs 1
讯享网const state = reactive({ count: 0 })watch( () => state.count, (count, prevCount) => { / … / })
export function watchEffect( effect: WatchEffect, options?: WatchOptionsBase): WatchStopHandle { return doWatch(effect, null, options)}
讯享网export function watch<T = any, Immediate extends Readonly<boolean> = false>( source: T | WatchSource<T>, cb: any, options?: WatchOptions<Immediate>): WatchStopHandle { return doWatch(source as any, cb, options)}
<input v-model=‘something’>相当于<input v-bind:value=“something” v-on:input=“something = \(event.target.value"></pre><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 16px; color: rgb(77, 77, 77); line-height: 26px; overflow: auto hidden;">如果在自定义组件中,v-model 默认会利用名为 value 的 prop 和名为 input 的事件,如下所示:</p><pre style='box-sizing: border-box; font-family: "Source Code Pro", "DejaVu Sans Mono", "Ubuntu Mono", "Anonymous Pro", "Droid Sans Mono", Menlo, Monaco, Consolas, Inconsolata, Courier, monospace, "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 14px; margin-top: 1.2em; margin-bottom: 24px; line-height: 22px; color: rgb(0, 0, 0);'>父组件:<ModelChild v-model="message"></ModelChild>子组件:<div>{{value}}</div>props:{ value: String},methods: { test1(){ this.\)emit(‘input’, ’小红’) },},
讯享网<script> // Vue.options 中会存放所有全局属性// 会用自身的 + Vue.options 中的属性进行合并 // Vue.mixin({ // beforeCreate() { // console.log(‘before 0’) // }, // }) debugger; const vm = new Vue({ el: ’#app’, beforeCreate: [ function() { console.log(‘before 1’) }, function() { console.log(‘before 2’) } ] }); console.log(vm);</script>
export function callHook(vm, hook) { // 依次执行生命周期对应的方法 const handlers = vm.\(options[hook]; if (handlers) { for (let i = 0; i < handlers.length; i++) { handlers[i].call(vm); //生命周期里面的this指向当前实例 } }}// 调用的时候Vue.prototype._init = function (options) { const vm = this; vm.\)options = mergeOptions(vm.constructor.options, options); callHook(vm, ”beforeCreate”); //初始化数据之前 // 初始化状态 initState(vm); callHook(vm, ”created”); //初始化数据之后 if (vm.\(options.el) { vm.\)mount(vm.\(options.el); }};// 销毁实例实现Vue.prototype.\)destory = function() { // 触发钩子 callHook(vm, ’beforeDestory’) // 自身及子节点 remove() // 删除依赖 watcher.teardown() // 删除监听 vm.$off() // 触发钩子 callHook(vm, ’destoryed’)}
讯享网function defieneReactive (obj, key, val){ const dep = new Dep(); … Object.defineProperty(obj, key, { … get: function reactiveGetter () { if(Dep.target){ dep.depend(); … } return val } … })}
class Dep { static target; subs; constructor () { … this.subs = []; } addSub (sub) { this.subs.push(sub) } removeSub (sub) { remove(this.sub, sub) } depend () { if(Dep.target){ Dep.target.addDep(this) } } notify () { const subs = this.subds.slice(); for(let i = 0;i < subs.length; i++){ subs[i].update() } }}
讯享网class Watcher { getter; … constructor (vm, expression){ … this.getter = expression; this.get(); } get () { pushTarget(this); value = this.getter.call(vm, vm) … return value } addDep (dep){ … dep.addSub(this) } …}function pushTarget (_target) { Dep.target = _target}
updateComponent = () => { vm._update(vm._render())}new Watcher(vm, updateComponent)
讯享网Object.defineProperty(obj, prop, descriptor)// obj 要定义属性的对象// prop 要定义或修改的属性的名称// descriptor 要定义或修改的属性描述符Object.defineProperty(obj,“name”,{ value:“poetry”, // 初始值 writable:true, // 该属性是否可写入 enumerable:true, // 该属性是否可被遍历得到(for…in, Object.keys等) configurable:true, // 定该属性是否可被删除,且除writable外的其他描述符是否可被修改 get: function() {}, set: function(newVal) {}})
import { mutableHandlers } from ”https://maimai.cn/article/baseHandlers”; // 代理相关逻辑import { isObject } from ”https://maimai.cn/article/util”; // 工具方法export function reactive(target) { // 根据不同参数创建不同响应式对象 return createReactiveObject(target, mutableHandlers);}function createReactiveObject(target, baseHandler) { if (!isObject(target)) { return target; } const observed = new Proxy(target, baseHandler); return observed;}const get = createGetter();const set = createSetter();function createGetter() { return function get(target, key, receiver) { // 对获取的值进行放射 const res = Reflect.get(target, key, receiver); console.log(“属性获取”, key); if (isObject(res)) { // 如果获取的值是对象类型,则返回当前对象的代理对象 return reactive(res); } return res; };}function createSetter() { return function set(target, key, value, receiver) { const oldValue = target[key]; const hadKey = hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); if (!hadKey) { console.log(“属性新增”, key, value); } else if (hasChanged(value, oldValue)) { console.log(“属性值被修改”, key, value); } return result; };}export const mutableHandlers = { get, // 当获取属性时调用此方法 set, // 当修改属性时调用此方法};








版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/206732.html