programing

VueJ의 동적 컴포넌트에 소품을 동적으로 전달s

goodcopy 2022. 7. 27. 22:12
반응형

VueJ의 동적 컴포넌트에 소품을 동적으로 전달s

동적인 견해가 있습니다.

<div id="myview">
  <div :is="currentComponent"></div>
</div>

연결된 Vue 인스턴스:

new Vue ({
  data: function () {
    return {
      currentComponent: 'myComponent',
    }
  },
}).$mount('#myview');

이를 통해 컴포넌트를 동적으로 변경할 수 있습니다.

제 경우, 세 가지 다른 컴포넌트가 있습니다.myComponent,myComponent1,그리고.myComponent2이렇게 전환합니다.

Vue.component('myComponent', {
  template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}

자, 이제 소품을 전달하고 싶습니다.myComponent1.

컴포넌트 타입을 변경할 때 이 소품들을 어떻게 패스할 수 있나요?myComponent1?

소품을 역동적으로 전달하려면v-bind동적 컴포넌트에 지시하고 소품 이름과 값을 포함하는 객체를 전달합니다.

동적 컴포넌트는 다음과 같습니다.

<component :is="currentComponent" v-bind="currentProperties"></component>

그리고 Vue의 경우,currentProperties는 현재 컴포넌트에 따라 변경될 수 있습니다.

data: function () {
  return {
    currentComponent: 'myComponent',
  }
},
computed: {
  currentProperties: function() {
    if (this.currentComponent === 'myComponent') {
      return { foo: 'bar' }
    }
  }
}   

자, 이제,currentComponentmyComponent에는,foo같은 성질'bar'그렇지 않으면 자산이 전달되지 않습니다.

계산된 속성을 사용하지 않고 개체를 인라인화할 수도 있습니다.

<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

V-Bind 관련 문서에 표시됨 - https://vuejs.org/v2/api/#v-bind

이렇게 만들 수도 있고...

comp: { component: 'ComponentName', props: { square: true, outlined: true, dense: true }, model: 'form.bar' }
     
<component :is="comp.component" v-bind="{...comp.props}" v-model="comp.model"/>

require를 통해 코드를 Import한 경우

var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')
and initalize the data instance as below

data: function () {
            return {
                currentView: patientDetailsEdit,
            }

컴포넌트에 할당되어 있는 경우 name 속성을 통해 컴포넌트를 참조할 수도 있습니다.

currentProperties: function() {
                if (this.currentView.name === 'Personal-Details-Edit') {
                    return { mode: 'create' }
                }
            }

저도 같은 과제를 안고 있습니다.이 문제는 다음과 같습니다.

<component :is="currentComponent" v-bind="resetProps"> 
   {{ title }}
</component>

그리고 대본은

export default { 
  …
  props:['title'],
  data() {
    return {
      currentComponent: 'component-name',
    }
  },
  computed: {
    resetProps() {
      return { ...this.$attrs };
    },
}
<div
    :color="'error'"
    :onClick="handleOnclick"
    :title="'Title'"
/>

난 리액션에서 왔고 이게 내 문제를 해결해준다는 걸 알았어

언급URL : https://stackoverflow.com/questions/43658481/passing-props-dynamically-to-dynamic-component-in-vuejs

반응형