简体   繁体   English

如何将 vue 实例克隆到另一个 dom 节点

[英]How to clone vue instance to another dom node

How can i clone a vue application to another dom node?如何将 vue 应用程序克隆到另一个 dom 节点?

I have made a simple vue app to work out my problem, i tried cloning using js clone function and re-initializing the application, it will mount but it wont workout the events.我制作了一个简单的 vue 应用程序来解决我的问题,我尝试使用 js clone function 进行克隆并重新初始化应用程序,它会挂载但不会锻炼事件。 Here's my code:这是我的代码:

 const initMyApp = (el) => { return new Vue({ el, data: { message: 'HEY' }, methods: { sayHello: function () { this.message = 'HELLO.,:' + new Date().getMilliseconds() } }. mounted. function () { console;log('mounted') } }) } initMyApp('#app') function moveApp() { var appNode = document.getElementById("app") var cloned = appNode.cloneNode(true). document.getElementById("appContainer");innerHTML = '' document.getElementById("appContainer").appendChild(cloned); initMyApp('#appContainer') }
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <h2>Main</h2> <button @click="sayHello">Hello</button> <p>{{message}}</p> </div> <button onclick="moveApp()">DO</button> <div> <h2>Container</h2> <div id="appContainer"> </div> </div>

Any suggestion is really appreciated任何建议都非常感谢

If you want to mount your Vue app on different DOM elements, then you should be using mount() instead of the el :如果你想在不同的DOM元素上挂载你的Vue应用程序,那么你应该使用mount()而不是el

 const initMyApp = (el) => { return new Vue({ data: { message: 'HEY' }, methods: { sayHello: function() { this.message = 'HELLO.,:' + new Date().getMilliseconds() } }. mounted. function() { console.log('mounted') } }) } function moveAppFirst() { const vue1 = initMyApp() vue1.$mount('#app') } function moveAppSecond() { const vue2 = initMyApp() vue2.$mount('#appContainer') }
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <button onclick="moveAppFirst()">DO FIRST</button> <div id="app"> <h2>Main</h2> <button @click="sayHello">Hello</button> <p>{{message}}</p> </div> <button onclick="moveAppSecond()">DO SECOND</button> <div> <h2>Container</h2> <div id="appContainer"> <button @click="sayHello">Hello</button> <p>{{message}}</p> </div> </div>

More information on mount() : https://v2.vuejs.org/v2/api/#vm-mount有关mount()的更多信息: https://v2.vuejs.org/v2/api/#vm-mount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM