1

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>

1 Answer 1

3

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

is there any chance you could explain more about the fat arrow and why it changes this.
@matt The lexical scope of this will be modified within the ready callback as jQuery provides the document as this instead. By using the fat arrow we change the lexical scope back to the bounding parent method's this which is the Vue component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.