起始:聊聊Vue

220 阅读1分钟

初识Vue

定义:Vue渐进式的JavaScript框架

Vue.js是什么:是一套构建用户界面的渐进式框架。区别于其他的框架,Vue的核心库只关注视图层。 只关注核心库会想到一种设计模式MVVM。

MVVM介绍

MVVM将数据模型数据双向绑定的思想作为核心,在view和model之间通过viewModel进行交互,即view数据的变化会同时修改数据源,而数据源的修改会反应到view上。

Vue的使用方式

script导入使用

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>

<script>
  const app = new Vue({
    el: '#app',
    data: {
      foo: 'foo',
      items: [1, 2, 3, 4],
    },
  });
</script>

Vue Cli

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

使用Vue使用的疑惑

  • 为什么必须要挂载在dom节点上
  • new Vuew({})是如何实现的
  • Vue的生命周期回调是如何实现的
  • 虚拟DOM是如何实现的

模仿Vue实现(简单探究)

挂载节点#app

<div id="app"></div>

通过构建Vue实例实现页面渲染

<script>
  const app = document.getElementById('app');
  function Vue(options) {
    
  }
  const vm = new Vue({})
  vm.node = document.createElement('h2')
  vm.node.textContent = '111'
  app.appendChild(vm.node)
</script>

改进对象的形式创建节点

会发现通过对象的方式创建节点看起来不是很直观,但却可以做到渲染、创建节点分离

<script>
  const app = document.getElementById('app');
  function Vue(options) {
    
  }
  const vm = new Vue({})
  // 通过js对象的方式创建DOM节点
  vm.vnode = [
    {
      elm: 'h2',
      tag: 'h2',
      children: [
        {
          elm: 'h2',
          text: '11'
        }
      ]
    }
  ]
  // 页面渲染
  for (const item of vm.vnode) {
    const dom = document.createElement(item.tag)
    if (item.children && item.children.length === 1) {
      dom.textContent = item.children[0].text
    }
    app.appendChild(dom)
  }
</script>

关于Vue生命周期的疑问

  • 生命周期是阻断式的吗
  • 生命周期是如何实现的

模拟的简版生命周期

<script>
  function Vue(options) {
    this.options = options
    this._events = Object.create(null) 
    eventMixin(this,'create',this.options['create']())
    callHook(this,'create')
  }

  Vue.prototype.$on = function(event,handler){
    var vm = this;
    vm._events[event] = vm._events[event] || [];
    vm._events[event].push(handler)
    return vm
  }

  Vue.prototype.$emit = function(event){
    var vm = this;
    if (vm._events[event]){
      vm._events[event].forEach((handler)=>{
        handler()
      })
    }
    return vm
  }

  function callHook(vm,name){
    vm.$emit(name);
  }

  function eventMixin(vm,event,fn){
    vm.$on(event,fn)
  }

  const vm = new Vue({
    create(){
      console.log('01');
    }
  })
</script>

Vue生态内容