我有一個要從 Vue2 移植到 Vue3 的應用程式。我沒有使用捆綁器,因為 Vue 只是在頁面上提供簡單的互動性。這是 Vue2 中的簡化版本:
// my-modal.js
var myModal = Vue.component('my-modal',
{
template:
`<div id="myModal">
<button @click.prevent="open=true">Open Modal</button>
<div v-if="open" >
<p>Hello from the modal!</p>
<button @click.prevent="open=false">Close</button>
</div>
</div>`,
data() {
return {
open: false
}
}
})
在 Vue 2 中這個作業;
<script src="https://unpkg.com/vue@2"></script>
<div id="app">
<div class="outer">
<h3>Modal Example - {{ message }}</h3>
<div>
<my-modal />
</div>
</div>
</div>
<script src="/js/my-modal.js"></script>
<script>
const app = new Vue(
{
el: '#app',
data() {
return {
message: 'Hello Vue!'
}
}
});
</script>
對于 Vue3,根據以下檔案:https ://v3-migration.vuejs.org/break-changes/global-api.html#a-new-global-api-createapp 我將事情切換到我期望的作業:
<script src="https://unpkg.com/vue@3"></script>
<div id="app">
<div class="outer">
<h3>Modal Example - {{ message }}</h3>
<div>
<my-modal />
</div>
</div>
</div>
<script src="/js/my-modal.js"></script>
<script>
Vue.createApp({
data()
{
return {
message: 'Hello Vue!'
}
}
}).mount('#app')
</script>
在 my-modal.js 檔案中,我將前幾行更改為使用 Global Vue:
const { createApp } = Vue;
const app = createApp({});
app.component('my-modal', ...
Vue 實體可以作業,但找不到該組件并顯示錯誤訊息:“無法決議組件:my-modal”。我嘗試將“組件”部分添加到 Vue 實體和其他一些沒有運氣的東西。
有什么建議么?
uj5u.com熱心網友回復:
來自的每個實體createApp()都是唯一的。也就是說,呼叫createApp()inindex.html不會回傳與上一次呼叫 in 相同的實體my-modal.js。
一種解決方案是在匯入之前宣告全域app實體:my-modal.js
<!-- index.html -->
<script>
window._app = Vue.createApp({?})
</script>
<script src="/js/my-modal.js"></script>
<script>
// finally mount
window._app.mount('#app')
</script>
// js/my-modal.js
window._app.component('my-modal', {?})
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466016.html
