簡體   English   中英

如何將 vue 實例克隆到另一個 dom 節點

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

如何將 vue 應用程序克隆到另一個 dom 節點?

我制作了一個簡單的 vue 應用程序來解決我的問題,我嘗試使用 js clone function 進行克隆並重新初始化應用程序,它會掛載但不會鍛煉事件。 這是我的代碼:

 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>

任何建議都非常感謝

如果你想在不同的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>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM