简体   繁体   中英

How to call a function after selecting an option from a select element in Vue?

I have a couple of options in a <select> element. How can I call a function when I choose an option?

Here is what I have so far in terms of the JS:

export default {
  name: 'Dropdown',
  methods: {
    onChange() {
      logout();
    },
  },
  computed: {
    logout() {
      console.log('logout);
    },
  },
};

My select menu looks like this: <select @change="onChange">...

When I select an option, I receive the following error: logout is not defined . Any ideas?

you need to use this to reference the instance, so it will be this.logout();

EDIT:

You need to create an onLogout in the methods property if you want to do something particular, a computed property is a reactive property that return something, it isn't really meant to do something that handle the logout.

As i see your logout computed property would be more about getting the current status of the user if he's logout or not, but it would be better to rename it.

So if you want to do something particular when the select change(like a logout method)

you need to adapt your component this way:

export default {
  name: 'Dropdown',
  methods: {
    onChange() {
      this.logout();
    },
    logout() {
     console.log('logout called');
    },
  },
  computed: {
    userStatus() {
    // return a state or something, but must return something
    return ...
    },
  },
};

I invite you to read this documentation to have better idea about computed property and methods

https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties https://v1.vuejs.org/guide/events.html

注销功能应该在方法对象的顶部,你可以使用 this.logout() 来引用它

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