V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
GrapeCityChina
V2EX  ›  推广

灵光一闪!帮你使用 Vue,搞定无法解决的“动态挂载”

  •  
  •   GrapeCityChina · 2021-10-27 11:20:12 +08:00 · 427 次点击
    这是一个创建于 904 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在一些特殊场景下,使用组件的时机无法确定,或者无法在 Vue 的 template 中确定要我们要使用的组件,这时就需要动态的挂载组件,或者使用运行时编译动态创建组件并挂载。

    今天我们将带大家从实际项目出发,看看在实际解决客户问题时,如何将组件进行动态挂载,并为大家展示一个完整的解决动态挂载问题的完整过程。

    无法解决的“动态挂载”

    我们的电子表格控件 SpreadJS 在运行时,存在这样一个功能:当用户双击单元格会显示一个输入框用于编辑单元格的内容,用户可以根据需求按照自定义单元格类型的规范自定义输入框的形式,集成任何 Form 表单输入类型。

    这个输入框的创建销毁都是通过继承单元格类型对应方法实现的,因此这里就存在一个问题——这个动态的创建方式并不能简单在 VUE template 中配置,然后直接使用。

    而就在前不久,客户问然询问我:你家控件的自定义单元格是否支持 Vue 组件比如 ElementUI 的AutoComplete

    由于前面提到的这个问题:

    沉思许久,我认真给客户回复:“组件运行生命周期不一致,用不了”,但又话锋一转,表示可以使用通用组件解决这个问题。

    问题呢,是顺利解决了。

    但是这个无奈的"用不了",却也成为我这几天午夜梦回跨不去的坎。

    后来,某天看 Vue 文档时,我想到 App 是运行时挂载到#app 上的。,从理论上来说,其他组件也应该能动态挂载到需要的 Dom 上,这样创建时机的问题不就解决了嘛!

    正式开启动态挂载

    让我们继续查看文档,全局 APIVue.extend( options )是通过 extend 创建的。Vue 实例可以使用$mount方法直接挂载到 DOM 元素上——这正是我们需要的。

    <div id="mount-point"></div>
     
    // 创建构造器
    var Profile = Vue.extend({
      template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
      data: function () {
        return {
          firstName: 'Walter',
          lastName: 'White',
          alias: 'Heisenberg'
        }
      }
    })
    // 创建 Profile 实例,并挂载到一个元素上。
    new Profile().$mount('#mount-point')
    
    

    按照SpreadJS自定义单元格示例创建 AutoCompleteCellType ,并设置到单元格中:

    function AutoComplateCellType() {
    }
    AutoComplateCellType.prototype = new GC.Spread.Sheets.CellTypes.Base();
    AutoComplateCellType.prototype.createEditorElement = function (context, cellWrapperElement) {
    //   cellWrapperElement.setAttribute("gcUIElement", "gcEditingInput");
      cellWrapperElement.style.overflow = 'visible'
      let editorContext = document.createElement("div")
      editorContext.setAttribute("gcUIElement", "gcEditingInput");
      let editor = document.createElement("div");
      // 自定义单元格中 editorContext 作为容器,需要在创建一个 child 用于挂载,不能直接挂载到 editorContext 上
      editorContext.appendChild(editor);
      return editorContext;
    }
    AutoComplateCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
        let width = cellRect.width > 180 ? cellRect.width : 180;
        if (editorContext) {
          // 创建构造器
          var Profile = Vue.extend({
            template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
            data: function () {
              return {
                firstName: 'Walter',
                lastName: 'White',
                alias: 'Heisenberg'
              }
            }
          })
          // 创建 Profile 实例,并挂载到一个元素上。
          new Profile().$mount(editorContext.firstChild);
        }
    };
    
    

    运行,双击进入编辑状态,结果却发现报错了

    [Vue 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.

    根据报错提示,此时候我们有两种解决办法:

    1. 开启 runtimeCompiler ,在 vue.config.js 中加入 runtimeCompiler: true 的配置,允许运行时编译,这样可以动态生成 template ,满足动态组件的需求
    2. 提前编译模板仅动态挂载,autocomplete 的组件是确定的,我们可以使用这种方法

    新建 AutoComplete.vue 组件用于动态挂载,这样可以挂载编译好的组件。

    <template>
      <div>
        <p>{{ firstName }} {{ lastName }} aka {{ alias }}</p>
      </div>
    </template>
    <script>
    export default {
      data: function () {
        return {
          firstName: "Walter",
          lastName: "White",
          alias: "Heisenberg",
        };
      },
    };
    </script>
     
     
    import AutoComplate from './AutoComplate.vue'
     
     
    AutoComplateCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
        let width = cellRect.width > 180 ? cellRect.width : 180;
        if (editorContext) {
          // 创建构造器
          var Profile = Vue.extend(AutoComplate);
          // 创建 Profile 实例,并挂载到一个元素上。
          new Profile().$mount(editorContext.firstChild);
        }
    };
    
    

    双击进入编辑状态,看到组件中的内容

    下一步,对于自定义单元格还需要设置和获取组件中的编辑内容,这时通过给组件添加 props ,同时在挂载时创建的 VueComponent 实例上直接获取到所有 props 内容,对应操作即可实现数据获取设置。

    更新 AutoComplate.vue ,添加 props ,增加 input 用于编辑

    <template>
      <div>
        <p>{{ firstName }} {{ lastName }} aka {{ alias }}</p>
        <input type="text" v-model="value">
      </div>
    </template>
    <script>
    export default {
      props:["value"],
      data: function () {
        return {
          firstName: "Walter",
          lastName: "White",
          alias: "Heisenberg",
        };
      },
    };
    </script>
    
    

    通过 this.vm 存储 VueComponent 实例,在 getEditorValue 和 setEditorValue 方法中获取和给 VUE 组件设置 Value 。编辑结束,通过调用$destroy()方法销毁动态创建的组件。

    AutoComplateCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
        let width = cellRect.width > 180 ? cellRect.width : 180;
        if (editorContext) {
          // 创建构造器
          var Profile = Vue.extend(MyInput);
          // 创建 Profile 实例,并挂载到一个元素上。
          this.vm = new Profile().$mount(editorContext.firstChild);
        }
    };
     
    AutoComplateCellType.prototype.getEditorValue = function (editorContext) {
        // 设置组件默认值
        if (this.vm) {
            return this.vm.value;
        }
    };
    AutoComplateCellType.prototype.setEditorValue = function (editorContext, value) {
        // 获取组件编辑后的值
        if (editorContext) {
          this.vm.value = value;
        }
    };
    AutoComplateCellType.prototype.deactivateEditor = function (editorContext, context) {
        // 销毁组件
        this.vm.$destroy();
        this.vm = undefined;
    };
    
    

    整个流程跑通了,下来只需要在 AutoComplate.vue 中,将 input 替换成 ElementUI 的 el- autocomplete 并实现对应方法就好了。

    结果

    让我们看看效果吧。

    其实动态挂载并不是什么复杂操作,理解了Vue示例,通过 vm 来操作实例,灵活的运用动态挂载或者运行时编译的组件就不是什么难事了。

    其实一切的解决方案就在 Vue 教程入门教程中,但是脚手架的使用和各种工具的使用让我们忘记了 Vue 的初心,反而把简单问题复杂化了。

    今天的分享到这里就结束啦,后续还会为大家带来更多严肃和有趣的内容~

    你有什么在开发中"忘记初心"的事情吗?

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2965 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 15:04 · PVG 23:04 · LAX 08:04 · JFK 11:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.