programing

Vue $route가 정의되지 않았습니다.

randomtip 2022. 8. 10. 20:59
반응형

Vue $route가 정의되지 않았습니다.

나는 Vue 라우터를 배우고 있다.그리고 나는 사용하지 않고 프로그램 내비게이션을 만들고 싶다.<router-link>템플릿 파일에 있습니다.내 라우터 및 뷰:

 router = new VueRouter({
        routes: [
            {path : '/videos',  name: 'allVideos', component: Videos },
            {path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
        ]
    });

    new Vue({
        el: "#app",
        router,
        created: function(){
            if(!localStorage.hasOwnProperty('auth_token')) {
                window.location.replace('/account/login');
            }

            router.push({ name: 'allVideos' })
        }
    })

디폴트로는 'allVideos' 루트를 누르면 해당 컴포넌트 안에 'editVideo' 버튼으로 리다이렉트할 수 있는 버튼과 방법이 있습니다.

<button class="btn btn-sm btn-warning" @click="editVideo(video)">Edit</button>

방법:

editVideo(video) {router.push({ name: 'editVideo', params: { id: video.id } })},

잘 되고 있어요.그러나 VideoEdit 컴포넌트 내에서 ID를 취득하려고 하면$route.params.id오류가 발생하였습니다.Uncaughed ReferenceError:

지금은 npm을 사용하지 않고 Vue와 Vuerouter의 CDN 버전만 사용하고 있기 때문인지도 모릅니다.해결방법은?감사합니다!

갱신: Vue dev 툴에서 컴포넌트 내부에 $route 인스턴스가 표시됨

갱신일 :

var VideoEdit = Vue.component('VideoEdit', {
          template: ` <div class="panel-heading">
                        <h3 class="panel-title">Edit {{vieo.name}}</h3>
                    </div>`,
                data() {
                    return {
                        error: '',
                        video: {},
                }
            },        
            created: function () {
                  console.log($route.params.id);
            },
  })

Sandeep Rajoria 덕분에

솔루션을 찾았습니다.this.$route제외하고$route컴포넌트 내부

추가 후 오류가 발생한 경우this

TypeError: Cannot read property '$route' of undefined

ES6 화살표 기능 대신 일반 기능을 사용해야 합니다.

data: function() {
    return {
      usertype: this.$route.params.type
    };
  },

이건 나한테 효과가 있었어.

import Vue from 'vue'
import Router from 'vue-router';

Vue.use(Router)

const router = new VueRouter({
    routes: [
        {path : '/videos',  name: 'allVideos', component: Videos },
        {path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
    ]
});

new Vue({
    el: "#app",
    router,
    created: function(){
        if(!localStorage.hasOwnProperty('auth_token')) {
            window.location.replace('/account/login');
        }

        this.$router.push({ name: 'allVideos' });
    }
})

vue v2 및 vue-router v2를 사용하는 경우 vue-cli에서 생성된 보일러 플레이트 방식으로 라우터에 액세스합니다(예를 들어 컴포넌트에서 라우터/index.js로 내보내기됨).

<script>
  import Router from '../router';

다음으로 코드 내에서 다음과 같은 라우터 기능을 사용할 수 있습니다.

Router.push('/contacts'); // go to contacts page

es6 화살표 기능을 사용하려는 사용자에게 @Kishan Baghela의 또 다른 대체 방법은 다음과 같습니다.

methods: {
        gotoRegister() {
            this.$router.push('register')
        }
    }

ES6 객체의 메서드 첫 번째 답변에서 설명한 바와 같이: 화살표 기능 사용

내 경우 이전 솔루션이 작동하지 않기 때문에 다음을 수행했습니다.

<script> import Router from '../router';

그러면 당신의 코드에서 당신은 이것을 사용할 수 있습니다.

this.$router.push('/contacts');

언급URL : https://stackoverflow.com/questions/41860578/vue-route-is-not-defined

반응형