如何在VueJS中强制DOM元素在App.vue组件中呈现

问题描述

我目前正在使用Clippy.js,这是老式Microsoft Agent的js实现。 发生问题是因为我想在VueJS项目的App.vue组件内渲染代理。不过,我似乎无法弄清楚如何将代理绑定到App.vue组件或其任何子代。

代理加载如下:

<system.web>
  <anonymousidentification cookieRequireSSL="true" />
  <authentication>
   <forms cookieSameSite="None" requireSSL="true" />
  </authentication>
  <sessionState cookieSameSite="None" />
  <httpCookies sameSite="None" requireSSL="true" />
  <roleManager cookieRequireSSL="true" />

  <compilation targetFramework="4.7">
    ...
  </compilation>
  ...
  <httpRuntime targetFramework="4.7"/>
</system.web>

代码来自我的Header.app组件中的方法,该组件是App.vue的子组件

链接到目录:https://github.com/pi0/clippyjs

解决方法

下面是一个简单的演示,用于集成clippy

关键是在clippy.load的回调中获取代理实例,然后通过调用代理实例提供的相关API来执行所需的操作。

Clippy.js将在<body>下添加额外的Dom元素,因此我们最好在必要时将其清除(例如:组件已损坏)。

无论如何,Clippy.js的实现基于通过JQuery的真实Dom,Vue基于虚拟节点。如果在Vue项目中使用Clippy.js,事情会变得有些复杂。

Vue.component('v-clippy',{
    template:`
        <div>
            <button v-show="!this.agent" @click="loadClippy()">Load Clippy</button>
            <button v-show="this.agent" @click="show()">Show</button>
            <button v-show="this.agent" @click="hide()">Hide</button>
            <button v-show="this.agent" @click="play()">Play</button>
            <button v-show="this.agent" @click="animate()">Animate</button>
            <button v-show="this.agent" @click="destroy()">Destroy</button>
        </div>
    `,props: {
      name: {
        type: String,default: 'Links'
      }
    },data () {
      return {
        agent: null
      }
    },mounted: function () {
      this.loadClippy()
    },methods: {
      loadClippy: function () {
        clippy.load(this.name,(agent) => {
          this.agent = agent
        })
      },show: function () {
        this.agent && this.agent.show()
      },hide: function () {
        this.agent && this.agent.hide()
      },play: function () {
        this.agent && this.agent.play('Searching')
      },animate: function () {
        this.agent.animate()
      },destroy: function () {
        this.agent._el.remove() // this.agent._el is the JQuery object binds to the Dom of Agent
        this.agent = null
      }
    }
})

new Vue ({
  el:'#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" type="text/css" href="https://gitcdn.xyz/repo/pi0/clippyjs/master/assets/clippy.css">
<script src="https://unpkg.com/jquery@3.2.1"></script>
<script src="https://unpkg.com/clippyjs@latest"></script>

<div id="app">
    <div>
        <h3>Test Clippy</h3>
        <div>
            <v-clippy></v-clippy>
            <v-clippy name="Merlin"></v-clippy>
        </div>
    </div>
</div>