programing

라우터 뷰에서 동일한 컴포넌트 간의 Vue 전환이 다시 마운트/생성되지 않음

javaba 2022. 7. 17. 11:34
반응형

라우터 뷰에서 동일한 컴포넌트 간의 Vue 전환이 다시 마운트/생성되지 않음

동일한 컴포넌트를 사용하는 경우(예: 2가지 버전)User.vue이러한 데이터는 데이터 내에서만 다르므로 이러한 데이터 간에 전환할 때 vue에서 생성되거나 마운트된 라이프사이클 함수는 사용되지 않습니다.

내 말은:

아무것도 바뀌지 않았어요.


하지만 다른 컴포넌트로 바꾸면Welcome.vue페이지, 그리고 다시 제 페이지로 돌아갑니다.User.vue컴포넌트는 정상적으로 동작합니다.이 경우,User.vue컴포넌트는 자체 생성된 기능을 사용하여 내 스토어에서 사용자 관련 데이터를 새로고침합니다.

예:

동작 원리


보시다시피 컴포넌트가 다시 렌더링되어 관련 사용자 데이터가 정상적으로 로드됩니다.

나의User.vue요소

<template>
  <div>
    <UserInfo
      :user-name="userName"
      :budget="budget"
    />
    <UserIncExp />
  </div>
</template>

<script>
import UserInfo from '../User/UserInfo.vue';
import UserIncExp from '../User/UserIncExp/_UserIncExp.vue';
export default {
  components: {
    UserInfo,
    UserIncExp
  },
  data() {
    return {
      userName: '',
      budget: ''
    };
  },
  computed: {

  },
  watch: {
    '$route.params.id': id => {
      console.log(id);
      this.loadUserDataFromState();
    }
    // this.userName = this.$store.state.users[this.$attrs.userId].userName;
    // console.log(this.userId);
  },
  created: function() {
    this.loadUserDataFromState();
  },
  methods: {
    loadUserDataFromState() {
      console.log('route changed');
      this.userName = this.$store.state.users[this.$attrs.userId].userName;
      this.budget = this.$store.state.users[this.$attrs.userId].salery;
      console.log(this.userName);
      console.log(this.budget);
    }
  },
};
</script>

<style>
</style>

User.vue다음과 같이 store.state에서 데이터를 가져옵니다.

  state: {
    users: [
      // {
      //   userName: 'John',
      //   salary: 2000,
      //   leftover: 0,
      //   inc: [],
      //   exp: [],
      //   active: false,
      // }
    ],
    // placeholder: true
  },

부모는App.vue중고품으로<router-link>를 참조해 주세요.

<template>
  <div id="app">
    <Navigation />
    <router-view />
  </div>
</template>

<script>
// import { mapState } from 'vuex';
import Navigation from './components/Navigation/_Navigation.vue';
export default {
  components: {
    Navigation
  },
  computed: {}
};
</script>

<style lang="scss">
#app {
  height: 1200px;
  width: 100vw;
  background-color: $dark;
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #ffffff;
  a:hover {
    color: $orange;
  }
  a {
    color: $white;
  }
  *:focus {
    box-shadow: 0 0 0 0.2rem rgba(233, 84, 32, 0) !important;
  }
}
</style>

마지막으로 필요에 따라 라우터 설정

import Vue from 'vue';
import VueRouter from 'vue-router';
import Welcome from '../views/Welcome.vue';
import User from '../components/User/_User.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Welcome',
    component: Welcome
  },
  {
    path: '/user/:userId',
    name: 'User',
    component: User,
    props: true
  }
];

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
});

export default router;

보고 있다$route.params.id대신$route.params.userId라우터 Configuration에서 param을 추가한 것과 같이/user/:userId

watch: {
  "$route.params.userId": { // <-- here 
    handler () {
      this.loadUserDataFromState();
    },
    immediate: true // will call handler on component mount / create as well, so no need to call fn on mounted again
    }
  },

대안

beforeRouteUpdate (to, from, next) {
 if (from.name === to.name) { // Call fn only when: route hasn't changed instead just query/params for the route has changed
  this.loadUserDataFromState();
 }
},

언급URL : https://stackoverflow.com/questions/60786268/vue-switching-between-same-components-in-router-view-will-not-mounted-created-ag

반응형