按vue3显示应用程序中的多个组件

xu3bshqb  于 2023-02-05  发布在  Vue.js
关注(0)|答案(2)|浏览(139)

我做了两个组件,并试图在vue3应用程序中显示它们。
我的html代码

<div id="app">
    <image_preview>
        URL: [[image]]
    </image_preview>
    <file_uploader>
       Counter:[[counter]]
    </file_uploader>
</div>

在javascript中

const ImagePreview = {
    data(){
        return {
            image:"test.png"
        }
    },
    mounted() {
    },   
    delimiters: ['[[', ']]']  
}
const Counter = {
    data() {
      return{counter: 0}
    },
    mounted() {
      setInterval(() => {
        this.counter++
      }, 1000)
    },
    delimiters: ['[[', ']]']  
  }

Vue.createApp({
    components:{
        "image_preview":ImagePreview,
        "file_uploader":Counter
    }
}).mount('#app')

但是,html中不显示任何内容
我哪里错了?

yyyllmsg

yyyllmsg1#

请重新阅读vue关于组件的文档,你知道你是否需要一个模板来呈现组件,我打赌你还没有读过vue关于组件的文档
以我为例,它会解决你的问题:

// </script><script type="module">
import { createApp, ref, onMounted } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'

const ImagePreview = {
  template: '#image_preview',
  setup() {
    return {
      image: 'test.png'
    }
  }
}
const Counter = {
  template: '#file_uploader',
  setup() {
    const counter = ref(0)
    
    onMounted(() => setInterval(() => counter.value++, 1_000))
    
    return { counter }
  }
}

const app = createApp({
  components:{
    "image_preview": ImagePreview,
    "file_uploader": Counter
  }
})
.mount('#app')
<div id="app">
    <image_preview>
        URL: [[image]]
    </image_preview>
    <file_uploader>
       Counter:[[counter]]
    </file_uploader>
</div>

<template id="image_preview">
  URL: {{ image }}
</template>

<template id="file_uploader">
  Counter: {{ counter }}
</template>
pkwftd7m

pkwftd7m2#

您的组件没有模板或呈现函数。如果添加了模板或呈现函数,您将看到以下内容:

const ImagePreview = {
    data(){
        return {
            image:"test.png"
        }
    },
    mounted() {
    },   
    delimiters: ['[[', ']]'],
    render(){return 'Hello from ImagePreview'}
}
const Counter = {
    data() {
      return{counter: 0}
    },
    mounted() {
      setInterval(() => {
        this.counter++
      }, 1000)
    },
    delimiters: ['[[', ']]'],
    render(){return 'Hello from Counter'}
  }

Vue.createApp({
    components:{
        "image_preview":ImagePreview,
        "file_uploader":Counter
    }
}).mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app">
    <image_preview>
        URL: [[image]]
    </image_preview>
    <file_uploader>
       Counter:[[counter]]
    </file_uploader>
</div>

相关问题