简体   繁体   中英

Vue: How to change route based on selected option, AND also show the default selected option in a <select> element?

I'm able to change the route based on the option selected in my Dropdown component. However, the select menu does not show the correct selected value onChange.

Here is my component:

<template>
  <select v-model="accountMenuOption" @change="onChange()">
    <option value="/">Page 1</option>
    <option value="/2">Page 2</option>
    <option value="/3">Page 3</option>
  </select>
</template>

<script>

export default {
  name: 'AccountDropdown',
  data() {
    return {
      accountMenuOption: '/',
    };
  },
  methods: {
    onChange() {
      this.$router.push(this.accountMenuOption);
    },
  },
};
</script>

When I select the second option, the route changes to /2 , which is great. However, once the route changes, the select element does not update by showing the default selected value as "Page 2". It just continues to show "Page 1" as the selected value. How can I make it so that the select element's default selected value is updated accordingly, after the route changes?

It works fine as in the following example :

 Vue.config.devtools = false; Vue.config.productionTip = false; const Page1 = { template: '<div>page 1</div>' } const Page2 = { template: '<div>page 2</div>' } const Page3 = { template: '<div>page 3</div>' } const routes = [{ path: '/', component: Page1 }, { path: '/2', component: Page2 }, { path: '/3', component: Page3 } ] const router = new VueRouter({ routes }) new Vue({ el: '#app', router, data() { return { accountMenuOption: '/', }; }, methods: { onChange() { this.$router.push(this.accountMenuOption); }, }, })
 <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <div id="app" class="container"> <select v-model="accountMenuOption" @change="onChange()"> <option value="/">Page 1</option> <option value="/2">Page 2</option> <option value="/3">Page 3</option> </select> <router-view></router-view> </div>

I ended up solving the issue by adding the following within the component export:

  created() {
    // Make sure the correct option is shown on load
    this.accountMenuOption = this.$router.history.current.fullPath;
  },
  watch: {
    // Watch for route changes
    $route(route) {
      // Change the value of the selected option
      this.accountMenuOption = route.path;
    },
  },

I'm new to Vue, so not sure why exactly this solves my problem, but it does. If anyone wants to explain, feel free to.

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