简体   繁体   中英

Can you call a computed property from a button click in Vue JS or should you always use a method?

I have the following code where I can either call a computed property ("edit") or a method ("edit2") from a button click:

methods: {
    edit2() {
      console.log(this.editMode);
      this.editMode = !this.editMode;
    },
  },
  computed: {
    edit: function () {
      console.log(this.editMode);
      this.editMode = !this.editMode;
    },
  }

and the html:

     <b-col md="3" class="my-3" style="float: left;">
        <b-button
          variant="outline-primary"
          class="px-3"
          size="sm"
          style="float: left;"
          @click="edit"
          >Edit</b-button
        >
      </b-col>

Calling "edit2" ie the method works fine. Calling "edit" the computed property gives the following error:

Error in v-on handler: "TypeError: Cannot read property 'apply' of undefined"

Can I ask why this is? Should one never call a computed property like this?

Thanks

Always use a method.

The computed property is a calculate variable that your return value is kept in cache. When this variable was change, the computed is reloaded.

If you have doubts, check the official document: https://v2.vuejs.org/v2/guide/computed.html

In official documentation there are many examples that help you understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM