programing

vue 라우터 링크를 vue 구성 요소에 연결하는 방법

prostudy 2022. 3. 27. 14:42
반응형

vue 라우터 링크를 vue 구성 요소에 연결하는 방법

나는 Javascript뿐만 아니라 Vue 프레임워크도 매우 생소하지만, 현재 Vue를 사용하여 사이트를 만들고 있으며, 사용자가 탐색할 수 있는 링크를 내 사이트 상단에 가지고 싶다.나는 이러한 링크를 만들기 위해 Vue 라우터(https://router.vuejs.org/guide/##)를 사용해 보았다.이쯤 되면 사용자가 탐색할 수 있는 작은 'About Us' 섹션을 만들고 싶을 뿐이다.그러나 URL이 'localhost:8080/#/about_us'로 변경되었음에도 불구하고 링크와 연결된 Vue 구성 요소는 표시되지 않는다.

나는 main.js로 내 코드를 다음과 같이 구성했다.

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

Vue.config.productionTip = false

export const eventBus = new Vue();
Vue.use(VueRouter);

const AboutUs = {template: '<div>about_us</div>'};

const route = [{path:'/about_us', component: AboutUs}];
const router= new VueRouter({route});

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

그리고 난 내 앱을 가지고 있어.로 설계된 vue(참고:나는 코드의 많은 부분을 간결함을 위해 필수적인 것으로 줄였다.

import AboutUs from './components/AboutUs.vue'
import { eventBus } from './main.js'

export default {
  data(){
    return {
      films: []
    }
  },
  components: {
  "about-us": AboutUs
  },
  mounted(){
    fetch('https://ghibliapi.herokuapp.com/films')
    .then(res => res.json())
    .then(films => this.films = films)
    .catch(error=> console.log(error))
    }

}
</script>
body {
  background-color: deepskyblue;
}
<h1>Ghibli Fandom Extravaganza</h1>
  <nav>
      <li><router-link to="/about_us">About us </router-link></li>
      <router-view></router-view>
  </nav>
  <p>List of Ghibli Movies: <films-list :films="films"/></p>
  <film-detail />

이 시점에서 나의 AboutUs 구성 요소는 어떤 단순한 HTML로 사이트에 대한 일부 정보를 보여주는 아주 기본적인 Vue일 뿐이다.

태그. 그러나 링크가 활성화되어 작동하지만, 다른 Vue 구성 요소가 계속 표시되는 동안 Vue의 정보는 표시되지 않으며, 이는 연결되지 않았음을 나타내는 것인가?나는 Vue Router 사이트의 튜토리얼을 따르려고 노력했지만, 나는 코드의 실제 작동 방식에 대한 메카니즘을 이해하지 못한다고 생각한다.누가 나에게 수정 사항을 추천해 줄 수 있니?

업데이트: 내 AboutUs에 대한 코드 입니다.부에를 하다

<template>
<div>
    <h1>This site is for examining the movies of Studio Ghibli</h1>
</div>

</template>

<script>
export default {
    name: 'about-us'

}
</script>

<style scoped>

</style>

나는 'aboutus' 부품을 수입할 필요가 없다고 생각한다.그냥 이렇게 쓰면 돼.<router-link to="about_us">About us </router-link>그리고 main.js는 이렇게 경로를 선언한다.const route = [{path:'/about_us',name:'about_us', component: () => import("path to about us file")}];

네가 제공한 코드 샘플은 좀 헷갈리는데, 그냥 통과하면 돼.imported을 똑바로 보다component의 재산.router입장권

완료한 위치:

const AboutUs = {template: '<div>about_us</div>'};

해당 라인을 다음으로 교체하십시오.

import AboutUs from './components/AboutUs.vue'

당신의 샘플에서 언제, 그리고 어떤 관련이 있는지 알 수 없다.components: {"about-us": AboutUs },그것은 필요하지 않다.

다음은 내 설정의 샘플이다.

라우터.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('../components/views/welcome')
  },
  {
    path: '/about-us',
    name: 'about-us',
    component: () => import('../components/views/about-us')
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router

main.js.

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

앱뷰

<template>

  <v-app v-cloak>

      <router-link :to="{ name: 'index' }">Welcome</router-link>
      <router-link :to="{ name: 'about-us' }">About Us</router-link>

      <router-view></router-view>

  </v-app>
</template>

<script>

export default {
  name: 'App'
}

</script>

구성 요소/구성 요소/주변 정보부에를 하다

<template>

  <div>This is the About Us page!</div>

</template>

<script>
  export default {
   name: 'about-us'
  }
</script>

이 샘플은 기록 모드를 사용한다.

기타 유의사항

라우팅할 때,mounted믿을 수 없다. 대신 어떤 가져오기 논리를 그것 자체의 것에 넣어야 한다.method호출할 때:

methods: {
  fetch () {
    // https://github.com/axios/axios
    axios.get('https://ghibliapi.herokuapp.com/films').then( ... )
  }
}

부르다this.fetch둘 다의 방법.beforeRouteUpdate그리고beforeRouteEnter대신에mounted, 의지할 수조차 없다.created에 의해 처리된 견해에 관한 한.vue-router.

Axios가 더 많은 기능, 기능 및 브라우저 호환성을 제공하기 때문에 Axios가 네이티브 가져오기 대신 제안된다.

대략 우리에.이러한 내비게이션 가드를 추가하는 경우:


<template>

  <div>This is the About Us page!</div>

</template>

<script>
  export default {
   name: 'about-us'

  methods: {
    fetch () {
      axios.get('https://ghibliapi.herokuapp.com/films').then( ... )
    }
  }

  // Will fire if you are already on the view but a parameter changes (dynamic routing)
  beforeRouteUpdate(to, from, next) {
     this.fetch()
     next()
  },

  // Will fire when you enter the view
  beforeRouteEnter(to, from, next) {
    this.fetch()
    next()
  },

}
</script>

둘 다 추가되어야 하고, 동시에 발포하지 않을 것임을 이해하고, 둘 중 하나만 실행될 것이다.fetch관련될 때 한 번

이렇게 하면 동적 라우팅을 사용할 때 발생할 수 있는 모든 문제를 해결할 수 있다.

폴더 구조

 src/
 + App.vue
 + main.js
 + router.js
 + vue.config.js
 + assets/
    + logo.png
 + components/
    + views/
       + welcome.vue
       + about-us.vue

이렇게 하면 설정 요구 사항이 해결되길 바란다.

참조URL: https://stackoverflow.com/questions/61032786/how-to-make-the-vue-router-link-connect-to-the-vue-component

반응형