Home > Net >  Showing muptiple components in an app by vue3
Showing muptiple components in an app by vue3

Time:02-03

I made two components and tried to show these in vue3 app.

my code in html

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

in 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')

However nothing appears in html

Where am I wrong?

CodePudding user response:

please re-read vue's documentation on components you know if you're going to need a template to render components and I bet you haven't read vue's documentation on components

follow my example and it takes care of your problem:

// </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>

CodePudding user response:

Your components don't have a template or a render function. If you add it, you see something:

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>

  • Related