如何在vue.js中使用CDN组件



我使用vue.js作为CDN。我需要一个如何构建应用程序以在index.html中显示组件的示意图的帮助。目前,我有以下结构:

<div id="app">
</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {

}

}).mount('#app')
</script>

component.js:

<template>
<div>
Test
</div>
</template>

export default {
data: () => ({
}),


}

您可以尝试定义Vue并使用.component

//in other file
const component1 = {
template: `<div> {{ item }} <p>{{ prop }}</p></div>`,
props: ['prop'],
data: () => ({ item: 'test' }),
}

const app = Vue.createApp({
data: () => ({ someData: 'prop' }),
})
app.component('test', component1)
app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
<test :prop="someData" />
</div>

component_one.html

<p>component one</p>

component_two.html

<p>component {{two}}</p>
<input type="text" v-model="two"/>

component_three.html

<p>component three</p>

app.html

<router-link to="/">one</router-link> | 
<router-link to="/two">two</router-link>
<component_three/>
<router-view />

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.41/vue.global.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.1.6/vue-router.global.js"></script>
<title>test</title>
</head>
<body>
<div id="app"/>
<script type="text/javascript" src="index.js"> </script>
</body>
</html>

index.js

const one = async () => {
let template = await fetch("component_one.html")
template = await template.text()
return ({
template: template,
setup() {/*...*/ }
})
}
const two = async () => {
let template = await fetch("component_two.html")
template = await template.text()
return ({
template: template,
setup() {
return {
two: Vue.ref("TWO"),
}
}
})
}
const three = async () => {
let template = await fetch("component_three.html")
template = await template.text()
return ({
template: template,
setup() {/*...*/ }
})
}
const app = async () => {
let template = await fetch("app.html")
template = await template.text()
return ({
template: template,
components: {
"component_three" : await three(),
},
setup() {/*...*/ }
})
}
const init = async () => {
const index = Vue.createApp(await app());       
const routings = VueRouter.createRouter({
history : VueRouter.createWebHashHistory(),
routes : [
{path:'/', component: await one()},
{path:'/two', component: await two()}
]
})
index.use(routings)
index.mount("#app")
}
init()

html文件以字符串形式读取。也许可以将它们放在后端/数据库服务器中。为了更快地加载,请对所有等待组件使用Promise.all([])。工作示例:www.julven.epizy.com/vuetest

以下是我在vue路由器上尝试的内容。我们可以将逻辑分离为组件。以下是replit 中的示例

index.html中,我们可以使用<script type="module">,这样我们就可以使用导入js文件。

组件/home/home.js中,importTemplate函数接受一个html文件路径,并将html文件作为字符串返回。其他vue属性如方法、数据可以放在export default {}中。

如果需要子组件,我们可以像index.html中那样使用app.component('bottomb', BottomBar)。然后<bottomb />可以在所有其他组件中使用,如home.html,而不仅仅是在index.html中。

最新更新