BleddP
BleddP

Reputation: 271

Cannot use Options API in Vue 3 with Webpack

I have a question about the Options API in Vue 3 which might be specific to my implementation with Webpack 5. From the docs and articles it seems that in Vue 3 you can use both the 'old' Options API and the 'new' Composition API interchangeably in Vue 3.

However when I have the following code in my Vue 3 app:

<template>
  <div class="blog-overview__filters">
    <button @click="filter()" class="filter filter__option">Click me</button>
  </div>
</template>

<script>
export default {
  name: "Filters",
  methods: {
    filter() {
      console.log('Hello')
    }
  }
};
</script>

I get the following warnings: Unhandled error during execution of native event handler $options.filter is not a function

When I use the setup function for the Composition API it works properly:

export default {
  name: "Filters",
  setup() {
    const filter = () => {
      console.log('Hello')
    }
    return {
      filter
    }
  }
};

The same goes for other Options API methods.

The below Options API code does nothing in Vue 3:

export default {
  name: "Blogs",
  data() {
    return {
      blogs: [],
    };
  },
  created() {
    let endpoint = "endpoints/blog-overview.json";
    axios
      .get(endpoint)
      .then((res) => {
        this.blogs = res.data.blogs;
      })
      .catch((err) => {
        console.log({ err });
      });
  },
};

But the Composition API works just fine:

import { onMounted, ref } from "vue";

export default {
  name: "Blogs",
  setup() {
    const blogs = ref([]);
    onMounted(() => {
      let endpoint = "endpoints/blog-overview.json";
      axios
        .get(endpoint)
        .then((res) => {
          blogs.value = res.data.blogs;
        })
        .catch((err) => {
          console.log({ err });
        });
    });
    
    return {
      blogs
    }
  },
};

Are we not supposed to be able to continue using the Options API in Vue 3?

My setup is: webpack: 5.65.0 vue: 3.2.26 vue-loader: 17.0.0 @vue/compiler-sfc: 3.2.26

Upvotes: 2

Views: 1636

Answers (1)

BleddP
BleddP

Reputation: 271

I figured it out, a few weeks ago when I updated the basic boilerplate for our agency's projects to Webpack 5 I added the below in the webpack config:

new webpack.DefinePlugin({
  __VUE_OPTIONS_API__: false,
  __VUE_PROD_DEVTOOLS__: false
})

But this turns the options API off, I believe to reduce bundle size and improve performance. Simply setting __VUE_OPTIONS_API__ to true did the trick for me.

Additionally I also realised I don't need @vue/compiler-sfc since I am using a Vue version of 3.2.13 or higher

Upvotes: 0

Related Questions