vue中的动态路由器路径验证

时间:2017-04-01 05:49:00

标签: javascript html vue.js

{path:'/ institute_details /:id',component:require('./ views / institutedetails / instdetails.vue')},

我想在路径重定向之前验证id

{path: '/institute_details/:id', component: require('./views/institutedetails/instdetails.vue')},



methods: {   
      validateData() {
        var re = new RegExp("^[a-zA-Z][0-9]{6}$")
        var string1=this.seatno
        var vm=this
        if(this.seatno==' ' || this.seatno.length==0 ){
          this.seatno=''
          alert("Enter Your Seat Number...!")
          this.$refs.seatno1.focus();
        }else if(!re.test(string1)){
          this.seatno=''
          alert("Invalid...!")
          this.$router.push({path:'/' })
        }
      }
    }
<div class="btn_result">
  <span v-on:click="validateData">
    <router-link :to="'institute_details/' + seatno " class="btn btn-success">View Path
    </router-link>
  </span>
</div>

2 个答案:

答案 0 :(得分:1)

您可以在组件中使用beforeRouteEnter挂钩。

其用法在官方的vue-router文档中指定。see vue-router document

组件中的代码示例

export default {
    data() {
        // define your component's data here.
    },

    methods: {
        validateDate() {
            // function to valiate your data
        },
    },

    beforeRouteEnter(to, from, next) {
        // check before enter the route
        // if check failed, you can cancel this routing

        // fake code here
        const isCheckPassed = checkWithSomeLogic();

        if (isCheckPassed) {
            next();
        } else {

            // cancel this routing
            // or redirect to the page you want with next function
            next({
                path: 'route you want to redirect to',
                query: {
                    // your query params here
                },
            });
        }
    },
};

希望它有所帮助。

答案 1 :(得分:0)

如果您只想切换到特定路由,并在语句if(to.fullPath.includes('/yoururl'))中对该添加条件应用逻辑,则next()