DOM 트리 변환 후 Vue.js 구성 요소를 마운트하여 vue 구성 요소를 추가합니다.
(아래) 필요한 유스케이스가 있습니다.mount
(정확한 용어일 경우) jQuery를 통해 DOM에 삽입된 Vue.js 컴포넌트템플릿을 사용하면 변환 옵서버를 셋업하거나 변환이 발생했을 때 트리거되는 특정 이벤트에 응답할 수 있습니다.
Vue.js v2를 사용하고 있습니다.
다음은 요점을 설명하기 위해 정리한 간단한 예입니다.
live jsFiddle https://jsfiddle.net/w7q7b1bh/2/
다음 HTML은 다음을 포함합니다.inlined-templates
2개의 컴포넌트
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div id="app">
<!-- The use of inline-template is required for my solution to work -->
<simple-counter inline-template>
<button v-bind:style="style" v-on:click="add">clicks: {{ counter }}</button>
</simple-counter>
<simple-counter inline-template>
<button v-on:click="counter += 1">{{ counter }}</button>
</simple-counter>
</div>
<button id="mutate">Mutate</button>
js:
// simple counter component
Vue.component('simple-counter', {
data: function() {
return {
counter: 0,
style: {
color: 'red',
width: '200px'
}
}
},
methods: {
add: function() {
this.counter = this.counter + 1;
this.style.color = this.style.color == 'red' ? 'green' : 'red';
}
}
})
// create the Vue instance
var initV = () => new Vue({
el: '#app'
});
// expose the instance for later use
window.v = initV();
// click handler that will add a new `simple-counter` template to the Vue.el scope
$('#mutate').click(function(){
$('#app').append(` <div is="simple-counter" inline-template>
<button v-bind:style="style" v-on:click="add">click to add: <span class="inactive" v-bind:class="{ active: true }">{{ counter }}</span></button></div>`)
// do something after the template is incerted
window.v.$destroy()
window.v = initV(); // does not work
})
코드에서 설명한 바와 같이 Vue 인스턴스를 재설치하는 것은 작동하지 않습니다.첫 번째 Vue 인스턴스화 시 컴포넌트의 템플릿이 최종 HTML로 변경되어 두 번째 인스턴스화 시도 시 템플릿이 존재하지 않고 컴포넌트가 존재하지 않는 이유를 이해합니다.mounted
변환 후 새로 추가된 부품을 찾아서 그것만 장착하고 싶은데 가능한가요?어떻게요?
업데이트: 새로운 Vue 인스턴스를 인스턴스화하여 전체와 달리 DOM의 특정 변환된 부분으로 설정함으로써 방법을 찾을 수 있었습니다.#app
트리:
$('#mutate').click(function(){
var appended =
$(`
<div is="simple-counter" inline-template>
<button v-bind:style="style" v-on:click="add">
click to add: {{ counter }}
</button>
</div>`
).appendTo($('#app'));
var newV = new Vue({el: appended[0]});
});
효과가 있는 것 같기도 하고, 보기에도 좋지 않은 것 같기도 하고, 또 어떤 의미가 있을지 모르겠습니다.
사용 사례:
Adobe Experience Manager(AEM)라고 하는 CMS의 Vue.js 컴포넌트를 쓰는 방법을 연구하고 있습니다.
컴포넌트를 작성하려면inlined-template
SEO와 HTL이라는 또 다른 템플릿 언어를 사용한 서버 사이드 렌더링의 장점을 제공합니다.
AEM 오서링은 컴포넌트가 (대화상자를 통해) 편집되면 해당 컴포넌트가 서버 측에서 다시 렌더링된 후 오래된 컴포넌트를 대체하기 위해 DOM에 다시 삽입됩니다.이 모든 작업은 Ajax 및 jQuery를 통해 수행됩니다(브라우저 새로고침 없음).
여기 예가 있습니다.
AEM 컴포넌트 템플릿:<button>${properties.buttonTitle}</button>
저자는 다음과 같이 할 수 있습니다.
- 작성자가 오서링 페이지를 방문하다
- 편집할 버튼 구성요소 대화상자를 엽니다.
- 버튼을 변경하다"new button title" 제목
- 저장
저장 시, ajax가 전송되고, 컴포넌트 HTML이 서버에서 다시 렌더링되어 반환되는 새로운 HTML입니다.이 HTML은 이제 jQuery를 통해 이전 HTML을 대체합니다(DOM 변환).
이는 정적 컴포넌트에는 문제가 없지만 Vue.js 컴포넌트일 경우 다른 컴포넌트를 마운트하면서 동적으로 마운트하려면 어떻게 해야 합니까?
이 문제의 간단한 해결 방법은 페이지를 새로 고치는 것입니다.하지만 그건 나쁜 경험일 뿐이야...더 나은 방법이 있을 거야
@liam 덕분에 나는 내 문제에 대한 적절한 해결책을 찾을 수 있었다.
HTML 템플릿으로 DOM을 변환한 후 해당 템플릿의 상위 요소에 대한 참조를 유지합니다.
예를 들어 다음과 같습니다.
var $template = $('<div is="simple-counter" inline-template> ..rest of template here.. <div>').appendTo('#app') // app is the Vue instance el or a child of it
새하여 " " " 를 할 수 .$template
을 the the라고 한다.el
컴포넌트가 다음과 같은 경우:
var simpleCounterComponent = Vue.component('simple-counter', {
data: function() {
return {
counter: 0,
style: {
color: 'red',
width: '200px'
}
}
},
methods: {
add: function() {
this.counter = this.counter + 1;
this.style.color = this.style.color == 'red' ? 'green' : 'red';
}
}
})
할 수 있는 일:
var instance = new simpleCounterComponent({
el: $template.get(0) // getting an HTML element not a jQuery object
});
이렇게 해서 새로 추가된 템플릿은 Vue 컴포넌트가 됩니다.
다음 질문에 근거한 이 바이올린을 예로 들어 보겠습니다.
런타임 생성 HTML에서 Vue 구성 요소를 인스턴스화하는 한 가지 방법은 다음과 같습니다.
var ComponentClass = Vue.extend({
template: '...',
});
var instance = new ComponentClass({
propsData: { name: value },
});
instance.$mount('#uid'); // HTML contains <... id="uid">
...
instance.$destroy(); // if HTML containing id="uid" is dropped
자세한 내용은 이쪽(이 사이트에 소속되어 있지 않습니다)
https://css-tricks.com/creating-vue-js-component-instances-programmatically/httpscss-tricks.com//
언급URL : https://stackoverflow.com/questions/48837002/vue-js-mount-component-after-dom-tree-mutation-to-add-a-vue-component
'programing' 카테고리의 다른 글
Firebase Firestore 'Reference' 데이터 유형은 무엇에 유효합니까? (0) | 2022.09.15 |
---|---|
벡터 반복, 스캔을 사용한 유형 오류 (0) | 2022.09.15 |
node.js를 사용하여 콜백이 호출될 때까지 함수를 대기시키는 방법 (0) | 2022.09.08 |
요구 방지필요한 스크립트 캐싱의 JS (0) | 2022.09.08 |
v-on 클릭, 조건이 충족된 경우에만 핸들러 추가 (0) | 2022.09.08 |