Home > Mobile >  Update list text after eventListener in vue
Update list text after eventListener in vue

Time:03-11

I have this problem with VUE. What I want is if I click on hello it should change the count us: 6 to Count us:7. Need help on this thing

<script>
   export default {
   data: function() {
         list = 5
    return {
      count: 1
    }
  },
  mounted() {
    
    console.log(this.count) 
    this.count = 5
    this.list=6
  },  
  methods:{
    // want to change
    say(){
      this.list = 7      
    }
    
  }
}
</script>

<template>
  Count is: {{ count }}
  count us : {{list}}
  <button @click="say()">
    hello
  </button>
</template>

CodePudding user response:

Your syntax was wrong, take a look at following snippet:

new Vue({
  el: "#demo",
  data() {
    return {
      list: [1,2,3,4],
    }
  }, 
  methods:{
    say(){
      this.list.push(this.list.length   1)   
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(item, i) in list" :key="i">
    {{ item }}
  </div>
  <button @click="say">
    hello
  </button>
</div>

CodePudding user response:

The reason why your code doesn't work as expected is because this inside the data function is not the component instance, it's the component context.

If you want to create a reactive property called list on the instance, you have to place a list property with a value other than undefined on the object returned by the data function.

Your example, fixed:

new Vue({
  el: '#app',
  data: {
    count: 1,
    list: 5
  },
  mounted() {
    console.log(this.count);
    this.count = 5;
    this.list = 6;
  },
  methods: {
    say() {
      this.list = 7
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div id="app">
  Count is: {{ count }}<br>
  List is: {{ list }}<br>
  <button @click="say">
    hello
  </button>
</div>

Now, if you change this.list to anything else in any method or component hook, the template will update accordingly.

Obviously, the data function doesn't have to be an arrow function.

data: function() {
  return {
    count: 1,
    list: 5 
  }
}

... works, too. Another note is that the data can also be an object. In your case

data: {
  count: 1,
  list: 5
}

...would work. However, this syntax is not recommended, as multiple instances of the same component would be sharing the same reactive data which is, in most cases, not the expected behavior.

  • Related