Search code examples
vuejs3laravel-mix-vue3

vue 3 data() not workink setup() working but why?


What is the difference? Why does one work and the other why not? The latter is included in the documentation but does not work. Is there something wrong with the webpack? I use laravel-mix

This code snippet work:

<template>
 <button @click="log">click me<button>
</template>
<script>
 export default {
  setup() {
   const log = () => console.log('run');
   return {
    log
   };
  }
 }
</script>

This code snippet didn't working:

<template>
 <button @click="log">click me<button>
</template>
<script>
 export default {
  methods: {
   log() {
    console.log('run');
   }
  }
 }
</script>

Solution

  • Both should not work, because you forgot to close your button and that should lead to a compiler error.

    Anyways, if you fix the errors in your markup both should work.

    Here you are using Vue's Options Api.

    <template>
      <button @click="log">click me</button>
    </template>
    
    
    <script>
    export default {
      methods: {
        log() {
          console.log("run");
        },
      },
    };
    </script>
    

    Here you are using Vue's Composition Api

    <template>
      <button @click="log">click me</button>
    </template>
    
    
    <script>
    export default {
      setup() {
        const log = () => console.log('run')
    
        return {
          log
        }
      }
    };
    </script>
    

    Maybe there's a chance you also disabled the Options Api in your webpack.mix.js?