TechDev
TechDev

Reputation: 433

data not updating when setting it in mounted document ready (VUEJS)

i assign a name inside the data. and in my mounted i want to save the variable in tthe data. however i try this.listcount = cc inside the mounted. but when i try to display listcount in my template it is giving me 0 which this value is the one i assign in data. i want the value to 2 not 0. can anyone help me thank you. this is the code.

https://codesandbox.io/s/pedantic-noyce-viq8q?file=/src/App.vue:0-713

App.vue

<template>
  <div id="app">List data: {{ listcount }}</div>
</template>

<script>
import $ from "jquery";
export default {
  name: "App",
  components: {},
  data() {
    return {
      listcount: 0,
    };
  },
  mounted() {
    $(document).ready(function () {
      var cc = 2;
      this.listcount = cc;
      console.log("LIST DATA", this.listcount);
    });
  },
  computed: {
    total() {
      console.log("TOTAL", this.listcount);
      return this.listcount;
    },
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Upvotes: 1

Views: 756

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50798

There is no need for the document.ready call within mounted(). this.listcount = cc works fine.

If you insist, the other issue is that .ready(function () { changes the scope of this, so you would at least need to use a fat arrow. Otherwise this will be the closure. With a fat arrow, this will be the Vue component. Observe:

$(document).ready(() => {
  var cc = 2;
  this.listcount = cc;
  console.log("LIST DATA", this.listcount);
});

Upvotes: 3

Related Questions