What causes an error in a basic Vue2 <script setup> example?

I previously developed Vue2 components using the class-based style and am now looking to transition my codebase to utilize the composition API. According to the documentation, the composition API and the script setup method for writing single file components are supported in Vue 2.7. However, I am encountering errors even when trying simple examples.

package.json

"vue": "2.7.14",

test.vue

<script setup>
  import {ref} from 'vue'

  const count = ref(0);
</script>

<template>
  <button @click="count++">{{ count }}</button>
</template>

The compilation is successful, but an error is thrown in the browser console:

App.js:144 Property or method "count" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. 

found in

---> <Test> at test.vue

Any insights as to why this is occurring?

Answer №1

If you're looking for a workaround, try utilizing the setup() function instead of using <script setup>, while still transitioning to the Composition API

<script>
import { ref } from "vue";

export default {
   setup() {
    const count = ref(0);
    return { count }
   }
};
</script>

<template>
  <button @click="count++">Counter: {{ count }}</button>
</template>

I have successfully implemented this in my Codesanbox


As per Vue Docs Migration to Vue 2.7, the <script setup> feature should be compatible with Vue 2.7.

However, I encountered challenges trying to get it to work in this Codesanbox

While the Composition API functions correctly, the issue lies with template compilation.

Answer №2

The reason for this issue stems from a compatibility problem with the version of Vue you are using. To resolve it, you can upgrade to the latest Vue version. However, if you prefer to stick with the traditional options API method, that is also perfectly fine. On the other hand, if you wish to transition to the composition API, then upgrading Vue is necessary. Additionally, note that the official state management library, Pinia, is designed for Vue3 and if you plan on incorporating state management in the future, you may encounter similar compatibility issues.

Answer №3

For my project using vue cli 4, I had previously included vue-template-babel-compiler. To update, I removed it from the vue.config.js file and ensured that the version of vue-loader in the package.json was 15.10.0+, referencing the features of vue-loader found in the release notes: compatibility with vue 2.7 and support for script setup.

// vue.config.js
chainWebpack(config) {
   // ...

   // Removed the following:

    // config.module
    //   .rule('vue')
    //   .use('vue-loader')
    //   .tap((options) => {
    //     options.compiler = require('vue-template-babel-compiler')
    //     return options
    //   })

    // ...
}

This approach worked well for me.

Answer №4

If you're facing a similar issue with Vite, in order to make the composition API compatible with Vue 2.7, you'll need to add the "@vitejs/plugin-vue2" package. You can find it here: https://www.npmjs.com/package/@vitejs/plugin-vue2

After installation, remember to import it into your vite.config.js file:

// vite.config.js
import vue from '@vitejs/plugin-vue2'

export default {
   plugins: [vue()]
}

Warm regards!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom Vue.js component for specific table cells within a table row - here's how!

My challenge is having related and neighboring table columns grouped within the same component in Vue.js. However, I'm facing a limitation with the template system where only one tag can be directly placed inside <template>. Typically, this wrap ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

What is the method for assigning a class name to a child element within a parent element?

<custom-img class="decrease-item" img-src="images/minus-green.svg" @click="event => callDecreaseItem(event, itemId)" /> Here we have the code snippet where an image component is being referenced. <template&g ...

Creating a mandatory 'Select' dropdown field in Vue.js

Hello, I am a beginner in VueJS and I am trying to make a select element from a drop-down list required. I attempted to add the required attribute as shown in the code below. Any suggestions on how to achieve this? Thanks. <v-select ...

Guide on extracting the ID within a for loop and incorporating it into a Vue.js function

In order to make an API request, I need to retrieve the id. However, whenever I try to include <a v-on:click="showRecipe({{inf.Id}})">Recipe</a> in my code, the entire page crashes. Removing this line resolves the issue. How can I pass the id ...

Display an icon button when a user edits the text in a text field, and make it disappear once clicked on

Figuring out how to incorporate a v-text-area with an added button (icon) that only appears when the text within the text area is edited, and disappears once it is clicked on, has proven to be quite challenging. Below is a simplified version of my code to ...

Vue.js does not support using nested v-for loops with p tags

I'm facing an issue with nesting 2 v-for loops in Vue.js. It seems simple, but for some reason, it's not working as expected and I can't figure out why. Looping through the users and displaying their names works perfectly. Even extracting t ...

Emphasize certain VueJS elements for focus

Currently, I am working with a Vue file and I'm interested in highlighting the active element. Can you recommend the most efficient method to achieve this? <li @click = "selectedComponent = 'appBugs1'"><i class="ion-bug"></i& ...

Having trouble submitting a date input form generated with vuejs on Safari browser

I am a huge fan of Vuejs and it's my go-to at work. The other day, I came across a rather perplexing scenario. If you have any insights into this, please do share. Here is the code in question: <script setup lang="ts"> import { ref ...

Adding HTML elements to a Vue Tooltip

Does anyone know how to implement a tooltip in Vue for a table cell that has more than 22 characters in its content? I was looking into using the v-tooltip library (https://www.npmjs.com/package/v-tooltip) Setting the tooltip's content with a simple ...

The Vue component should trigger the display of data in a Bootstrap modal based on the row of the button that was

Here is a sample code snippet demonstrating how data is fetched from the database: <table class="table table-bordered"> <thead> <tr><th>User ID</th><th>Account Number</th><th>Accou ...

The functionality of Jquery is successfully integrated into a specific function, however it seems to only work for one of the calls. To make the other call work,

After a user makes a selection, I am attempting to reset the 'selected' item. This process calls the Vue function tS() shown below. The issue lies with the first call $('#sel1').prop('selectedIndex',0);, as it only seems to wo ...

Trigger Vue method when the size of a div element changes

Is there a way to trigger a method every time the dimensions (width or height) of a div element change? <template> <div> </div> </template> <script> export default { methods: { updateSize() { // ...

What is the best way to send user input text to a Vue method using v-on:change?

I am trying to pass the input value from my HTML to a Vue method called checkExist(). I need to get this value within the checkExist() method. Can anyone provide advice on how I can achieve this? I am new to Vue and could use some guidance. HTML: <inp ...

Vue.Js allows developers to easily set a default selected value in a select dropdown menu

Having trouble with getting the default selected value using select in VueJs. I've attempted two different approaches: Using id and v-model fields in the select like this: <select v-model="sort_brand" id="sort-brand" class="form-control"> ...

Troubleshooting Vue.js nested v-for with <tr> tag problem

Why does Vue complain about undefined properties when I try nesting a <tr> inside a <tr> with a v-for binding on each? <table> <thead></thead> <tbody> <tr v-for="item in items"> <td>{{ item.nam ...

Error message: The Modelviewer is unable to load the local file, displaying the message "Unauthorized to access local resource."

For my WebAR project, I am utilizing Google's ModelViewer. In my vue.js project, I have a component that loads the model using the <model-viewer> attribute. My goal is to set the src attribute of the model-viewer to the absolute path of the .gl ...

Understanding the separation and communication techniques in Vue.js components

I recently developed a small vuejs application and I find myself getting confused with the functioning of components. Here is the code snippet that I have been working on: <div id="app"> <div v-if="loggedIn"> <nav> <r ...

Vue Page fails to scroll down upon loading

I am facing a challenge with getting the page to automatically scroll down to the latest message upon loading. The function works perfectly when a new message is sent, as it scrolls down to the latest message instantly after sending. I've experimented ...