What are the reasons behind the code not functioning properly while utilizing 'vue-property-decorator' in Vue.js with TypeScript?

I am currently working on a project using Vue.js and TypeScript, but I am facing an issue with 'vue-property-decorator'. I have two code snippets that are supposed to achieve the same result, but only one is working. Can someone please help me identify the mistake I have made?

Here is the code that works:

<script lang="ts">
import Vue from "vue";
import axios from "axios";
export default Vue.extend({
  name: "DetailPage",
  props: ["id"],
  data() {
    return {
      profile: [{}] as Array<object>
    };
  },
  methods: {
    findProfile(id?: string) {
      this.profile = [];
      axios
        .get("https://api.unsplash.com/photos/" + this.id, {
          headers: {
            Authorization: `Client-ID ${process.env.VUE_APP_MYVUE}`
          }
        })
        .then(res => {
          this.profile = res.data;
        })
        .catch(() => {
          this.profile = [];
        });
    }
  },
  watch: {
    $route(to: string, from: string) {
      this.findProfile();
    }
  },
  beforeMount() {
    this.findProfile();
  }
});
</script>

However, the code below using 'vue-property-decorator' does not work:

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import axios from "axios";

export default class DetailPage extends Vue {
  @Prop() readonly id!: string;
  private profile: Array<object> = [];
  findProfile(id?: string) {
    const profile: Array<object> = []
    axios
      .get("https://api.unsplash.com/photos/"+ this.id , {
        headers: {
          Authorization: `Client-ID ${process.env.VUE_APP_MYVUE}`
        }
      })
      .then(res => {
        console.log(res.data);
      });
      
  }
  
  @Watch("$route", { immediate: true, deep: true })
  onUrlChange(to: any, from: any) {
    this.findProfile();
  }
  beforeMount() {
    this.findProfile();
  }
}
</script>

Any assistance is greatly appreciated!

Answer №1

The @Component decorator signifies that the class is a Vue component

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import axios from "axios";

 @Component({
        name: 'ComponentName',
        components: {example, exampleTwo}
    })

export default class DetailPage extends Vue {
  @Prop() readonly id!: string;
  private profile: Array<object> = [];
  findProfile(id?: string) {
    const profile: Array<object> = []
    axios
      .get("https://api.unsplash.com/photos/"+ this.id , {
        headers: {
          Authorization: `Client-ID ${process.env.VUE_APP_MYVUE}`
        }
      })
      .then(res => {
        console.log(res.data);
      });
      
  }
  
  @Watch("$route", { immediate: true, deep: true })
  onUrlChange(to: any, from: any) {
    this.findProfile();
  }
  beforeMount() {
    this.findProfile();
  }
}
</script>

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

Interpolating SVG and HTML attributes in Vue.js

Wondering if this is the proper method to interpolate a value into an svg attribute using Vue. It seems to be effective for me, but I can't find any mention of it in their documentation. <svg :stroke-width="`${strokeWidth} px`" > ...

What is the process for extracting a literal expression from a customized directive in Vue.js 2?

I am in the process of migrating a custom Vue 1.x directive to Vue 2.x, and I'm facing an issue where I can't retrieve my expressions as literals anymore. Consider this example for my custom directive: <div v-custom="file.txt"></div> ...

How to Build Two Navbars in BootstrapVue with a Sticky Bottom Navbar at the Top

My current project involves creating two navigation bars. The first navbar at the top consists of just a brand logo, while the second navbar at the bottom serves as the main navigation menu. I want the top navbar to scroll off the screen when users scroll ...

What is the best way to deliver a file in Go if the URL does not correspond to any defined pattern?

I am in the process of developing a Single Page Application using Angular 2 and Go. When it comes to routing in Angular, I have encountered an issue. For example, if I visit http://example.com/, Go serves me the index.html file as intended with this code: ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

Avoiding type errors in d3 v5 axis by using Typescript

I am new to TypeScript and I have some code that is functioning perfectly. I believe if I define a type somewhere, d3's generics will come into play? Within my code, I have an xAxis and a yAxis. Both are the same, but D3 seems to have an issue with t ...

Utilize ngClass for every individual section

I have completed the implementation of all UI components, which are visually appealing. https://i.sstatic.net/hxJQr.png Here is the data structure I am using: public filters = [ { tag: 'Year', label: 'ye ...

Matching TypeScript values and types does not function as intended

Recently, I delved into TypeScript to work on my new AngularJS project. However, I encountered an issue where the id, which is supposed to be of type number, is actually being treated as a string. Have I overlooked something in my code? interface IRout ...

Issue encountered while attempting to right-click on Vue.js application

Whenever I try to right-click on my Vue.js and Vuex application, I encounter an error after each click: Uncaught ReferenceError: o is not defined at HTMLDocument.document.addEventListener.t (:1:784) This issue is occurring in the VM file. I trie ...

Building a Search Object using Template String Types

Here is a type definition that allows for specific responses: type Response = 'n_a' | 'n_o' | 'yes' | 'no' I want to create a type that ensures underscores are replaced with slashes: type ReplaceUnderscoreWithSlash& ...

My previously functioning TypeScript code suddenly ceased to work after I ran the yarn install command

Everything was running smoothly with my TypeScript code, both locally and on the server. However, after restarting the production code, I encountered errors (which required me to reinstall packages with yarn install). Strangely enough, when I try to yarn i ...

Tips on transforming current JSON into an alternate JSON format

Using React with TypeScript, I have a JSON data set of employees categorized by their department. Here's a snippet of the JSON data: [ { "department": 1, "name": "Test", "age": 32, "contact": 242222120, "id": 1 }, { "department": 1, "name": "Te ...

Unable to assign a value to an element obtained from the Axios response in React

I'm having trouble mapping an array, it doesn't seem to be working. You can find the code here : https://codepen.io/ilaan16/pen/eYRKgOm setUtils(result.data); if (!utils) { console.log("ERROR_UTILS", result); } else if ...

Invoke the parent's trigger method from a child component nested within a router in Quasar Framework (Vue)

I've configured my nested routes in the router using the Quasar framework (vue 3) like this: const routes = [ { path: "/", component: () => import("layouts/myLayout.vue"), children: [ { path: "&q ...

Guide on integrating google play services into a nativescript plugin seed?

I am developing a plugin for NativeScript using the recommended nativescript-plugin-seed available at this link. In my plugin, I require access to the Google Location service, but I am facing issues with accessing it. In order to implement the required de ...

Fetching values from dynamically generated elements in a Vue.js loop

I am currently working on creating a table that includes checkboxes and text fields based on an array of items, essentially building a "questionnaire" where the questions are pulled from a database. My question now is how can I efficiently retrieve inform ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Explaining the defineAsyncComponent Method in Vue 3

Recently, I've been exploring the vue3-beta release and stumbled upon a new feature called defineAsyncComponent. Surprisingly, there's not much information about it online. I'm curious about its use-case and when it should be used. How does ...

Enforcing Type Safety on String Enums in Typescript Using the 'const' Assertion

I am trying to use an enum for type checking purposes. Here is the enum I have: enum Options { Option1 = "xyz", Option2 = "abc" } My goal is to create a union type of 'xyz' | 'abc'. However, when I attempt to d ...

What is the best way to export Class methods as independent functions in TypeScript that can be dynamically assigned?

As I work on rewriting an old NPM module into TypeScript, I encountered an intriguing challenge. The existing module is structured like this - 1.1 my-module.js export function init(options) { //initialize module } export function doStuff(params) { ...