AngularOne
AngularOne

Reputation: 2860

How can I use Vue2 old component (.vue file) with a new Vue3 project?

Vue3 version is out, but I don't see any example of using old components code with the new version. How come?

Here is my index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue 3 Example using Vue 2 component</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <h1>{{ product }}</h1>    
      <my-old-vue-component :my-prop="'my string in here'"></my-old-vue-component>
    </div>

      <script src="./main.js"></script>
      <script src="./myOldVueComponent.vue"></script>

    <!-- Mount App -->
    <script>
      const mountedApp = app.mount('#app')
    </script>
  </body>
</html>

Here is my main.js:

const app = Vue.createApp({
  data() {
      return {
          product: 'my product',
      }
  }
})

Here is my old simple Vue2 component (myOldVueComponent.vue):

<template>

    <div>
        {{myProp}}
    </div>

</template>

<script>

  
    export default {
        name: "myOldVueComponent",
        props: {
            myProp: { type: String }
        },
        data() {
            return {
               
        },
       
    }

</script>

I'm getting error on the import of ".vue" file: uncaught SyntaxError: Unexpected token '<' (meaning the <template> tag inside my old component.

Upvotes: 4

Views: 9867

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10176

Vue2 components works in Vue3. That is not the issue in your code.


The problem is here:

<script src="./myOldVueComponent.vue"></script>

You can't import .vue files directly in a browser. You could not do it in vue 1,2 and you can't yet in vue 3. The browser is not able to understand that syntax, there needs to be a bundler that converts your code is something that can be used by the browser. The most popular bundlers are webpack, rollup ecc ecc

See: https://v3.vuejs.org/guide/single-file-component.html#for-users-new-to-module-build-systems-in-javascript

I highly recommend using the Vue cli to setup your project, especially if you are a beginner to the npm/bundlers world

Upvotes: 7

Related Questions