VueJS Migration from 2X to 3X Not Working

288 views Asked by At

I'm trying to convert a legacy app from Vue 2 to Vue 3. I'm not super familiar with Vue, I'm trying to follow the new migration template they provide on their docs website but I'm running into issues. I'm not getting any JS console errors, but my Vue code is no longer rendering anymore.

Existing Code

<script>
    var vm = new Vue({
        el: "#app",
        data: {
            applications: []
        },
        created: function () {
            console.log('Vue App Created'); 
            this.loadModel();
        },
        methods:
        {
            loadModel: function () {
                var url = "/Home/ApplicationData";
                $.get(url, function (resp) {
                    console.log(resp); // Note: For Testing
                    vm.applications = resp;
                });
            }
        }
    });
</script>

My Attempt at Vue 3 Migration

<script>
  Vue.createApp({
    data() {
      return {
        applications: []
      }
    },
    created() {
        console.log('Vue App Created'); 
        this.loadModel();
    },
    methods: {
        loadModel: function () {
            var url = "/Home/ApplicationData";
            $.get(url, function (resp) {
                console.log(resp); // Note: For Testing
                vm.applications = resp;
            });
        }
    }
  }).mount('#app')
</script>

HTML

<div id="app">
<ul>
    <li v-for="application in applications">{{ application.name }} - {{ application.url }}</li>
</ul>
</div>
1

There are 1 answers

0
tony19 On BEST ANSWER

The main issue is here:

vm.applications = resp;

The old code used vm to refer to the root component, but it's not assigned in your new code. However, that vm reference was never really necessary. It could've been avoided by using an arrow function instead of the regular function.

  1. Change the $.get callback from a regular function into an arrow function.

  2. Replace vm with this.

Vue.createApp({
  ⋮
  methods: {
    loadModel: function () {
      var url = "/Home/ApplicationData";
                    1️⃣
      $.get(url, (resp) => {
          2️⃣
        this.applications = resp;
      });
    }
  }
}).mount('#app')

<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<div id="app">
<ul>
    <li v-for="application in applications">{{ application.name }}</li>
</ul>
</div>

<script>
  Vue.createApp({
    data() {
      return {
        applications: []
      }
    },
    created() {
        console.log('Vue App Created'); 
        this.loadModel();
    },
    methods: {
        loadModel() {
            var url = "//jsonplaceholder.typicode.com/users";
            axios.get(url).then((resp) => {
                console.log(resp); // Note: For Testing
                this.applications = resp.data;
            });
        }
    }
  }).mount('#app')
</script>