DEV Community

Discussion on: Start writing Vue3 now

Collapse
 
yellow1912 profile image
yellow1912

Can we mix code with view or we have to choose between old and new style? If we can mix code migration would be much easier and can be done step by step.

Collapse
 
dasdaniel profile image
Daniel P πŸ‡¨πŸ‡¦

Not sure I understand the question, but if you mean whether the Composition API (using setup function) that's available in Vue3 is mandatory, or precludes one from using class-based component definition (Γ  la Vue2). The answer is that you can mix them. Here is an example that has two components (using same template)

jsfiddle.net/dapo/9hunLqgk/

<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app"></div>

<template id="appTemplate">
  <h1>H1: App</h1>
  <my-v2-component name="Pacho"></my-v2-component>
  <my-v3-component name="El Navigante"></my-v3-component>
</template>

<template id="componentTemplate">
  A {{type}} component
  <h3>
    {{greeting}}
  </h3>
</template>
const app = Vue.createApp({
  template: document.getElementById("appTemplate").innerHTML
})

app.component('my-v2-component', {
  template: document.getElementById("componentTemplate").innerHTML,
  props: {
    name: { default: ''}
  },
  data(){
    return {
        type: 'class-based'
    }
  },
  computed: {
    greeting() {
      return `Salutations ${this.name}`
    }
  }
})

app.component('my-v3-component', {
  template: document.getElementById("componentTemplate").innerHTML,
  props: {
    name: { default: ''}
  },
  setup() {
    const type = Vue.ref('Composition-API')
    const greeting = Vue.computed(() =>{
      return `Salutations ${this.name}`
    })
    return {
        type,
        greeting
    }
  }
})

app.mount('#app')
Collapse
 
yellow1912 profile image
yellow1912

Exactly what I mean, and thank you very much for the sample code.