首頁 > web前端 > Vue.js > 主體

帶你使用Vue搞定無法解決的'動態掛載”

青灯夜游
發布: 2022-09-05 11:30:02
轉載
2352 人瀏覽過

帶你使用Vue搞定無法解決的'動態掛載”

在一些特殊場景下,使用元件的時機無法確定,或者無法在Vue的template中確定要我們要使用的元件,這時就需要動態的掛載元件,或使用執行時間編譯動態建立元件並掛載。

今天我們將帶大家從實際專案出發,看看在實際解決客戶問題時,如何將元件進行動態掛載,並為大家展示一個完整的解決動態掛載問題的完整過程。

無法解決的「動態掛載」

#我們的電子表格控制項SpreadJS在運行時,存在這樣一個功能:當使用者雙擊儲存格會顯示一個輸入框用於編輯儲存格的內容,使用者可以根據需求按照自訂儲存格類型的規格自訂輸入框的形式,整合任何Form表單輸入類型。

這個輸入框的創建銷毀都是透過繼承單元格類型對應方法實現的,因此這裡就存在一個問題——這個動態的創建方式並不能簡單在VUE template中配置,然後直接使用。 【相關推薦:vuejs影片教學

#而就在前不久,客戶問然詢問我:你家控制項的自訂儲存格是否支援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 templates into render functions, or use the compiler-included build.

根據報錯提示,此時候我們有兩種解決方法:

    開啟runtimeCompiler,在vue.config.js中加入runtimeCompiler: true的配置,允許執行時間編譯,這樣可以動態產生template,滿足動態元件的需求
  • 提前編譯模板僅動態掛載,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的初心,反而把簡單問題複雜化了。

今天的分享到這裡就結束啦,後續還會為大家帶來更多嚴肅有趣的內容~

更多程式相關知識,請造訪:程式設計入門! !

以上是帶你使用Vue搞定無法解決的'動態掛載”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:cnblogs.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!