Vue.js 컴포넌트를 동적으로 추가 또는 삭제하는 방법(프로그래밍 또는 즉시)
이것은 제 코드입니다.이것은 샘플 코드입니다.아래가 유효하면, 제가 작업하고 있는 다른 것을 구축하는 데 도움이 됩니다.
<template>
<div id="wrapper">
<div id="divOne">
<!-- Add or remove component here dynamically -->
</div>
<div id="divTwo">
<!-- Add or remove component here dynamically -->
</div>
<!-- There will be more divs like #divOne #divTwo above -->
<div>
<input type="radio" id="one" value="divOne" v-model="pickedDiv">
<label for="one">One</label>
</div>
<div>
<input type="radio" id="two" value="divTwo" v-model="pickedDiv">
<label for="two">Two</label>
</div>
<button @click="addComponent">Add Component</button>
</div>
</template>
<script>
import SomeComponent from './SomeComponent'
export default {
data() {
return {
pickedDiv: '',
pickedDivPreviously: ''
propItems: ['item1', 'item2']
}
}
methods: {
addComponent () {
//-- This is not working code but I need something like this --//
this.pickedDivPreviously = this.pickedDiv // event not sure how to get previously selected div
const divThatIsPicked = document.getElementById(this.pickedDiv)
const divThatWasPickedPreviously = document.getElementById(this.pickedDivPreviously)
// code here to remove/empty/destroy old component from 'divThatWasPickedPreviously'
divThatWasPickedPreviously.innerHTML = ""
// code here to add new component in 'divThatIsPicked'
divThatIsPicked.appendChild('<some-component :someProp="propItems" @someEvent="someFn">')
}
}
}
</script>
실제 질문에 대한 답변을 방해하고 싶지는 않습니다만, 제가 무엇을 하고 있는지 궁금하신 분은 이것을 확인해 주세요:) 여기에서는 임의의 행 항목을 클릭했을 때 행 끝에 새로운 아이 DIV를 추가하려고 합니다.
위의 실제 질문보다 vue로 변환해 주시면 감사하겠습니다.어려워도 실제 질문에서 벗어나지 말아주세요:)
나는 제임스의 도움을 받았다.포럼의 톰슨.vuejs.org, 이 솔루션을 통해 문제가 해결되지는 않았지만 Vue.js를 사용할 때의 제한이나 가능성을 이해할 수 있었습니다.
James Thomson은 다음과 같이 말합니다.
그래, 네 예제 코드는 절대 작동하지 않을 거야.Vue를 사용하는 경우 DOM 지향(jQuery 등)이 아닌 데이터 지향적 사고방식이 필요합니다.
SO 포스트에서 인용한 내용:
여기서 행 항목을 클릭하면 행 끝에 새 하위 DIV를 추가하려고 합니다.
이것이 이 토픽의 최종 목표라고 생각합니다.예를 들면, https://codepen.io/getreworked/pen/XZOgbm?editors=1010 를 참조해 주세요.
let Welcome = {
template: `
<p @click="toggleMsg()">Welcome {{ msg }}!</p>
`,
data () {
return {
msg: 'home'
}
},
methods: {
toggleMsg () {
return this.msg = this.msg === 'home' ? 'back' : 'home';
}
}
}
const App = new Vue({
el: '#app',
data: {
children: [
Welcome
]
},
methods: {
add () {
this.children.push(Welcome);
},
}
});
<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<template v-for="(child, index) in children">
<component :is="child" :key="child.name"></component>
</template>
<button @click="add()">Add Another</button>
</div>
또는 렌더링 기능을 사용하여 유연성을 높일 수 있습니다.https://jsfiddle.net/jamesbrndwgn/ku7m1dp0/9/
const Reusable = {
template: '<div>{{ name }} {{ bar }}</div>',
props: {
name: {
type: String
}
},
data () {
return {
bar: 'Bar'
}
}
}
const App = new Vue({
el: '#app',
data: {
items: []
},
methods: {
addComponent () {
const renderComponent = {
render (h) {
return h(Reusable, {
class: ['foo'],
props: {
name: 'Foo'
}
})
}
}
this.items.push(renderComponent)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
<div id="app">
<component v-for="item in items" ref="itemRefs" :is="item" :key="item.name"></component>
<button @click="addComponent">Add Component</button>
</div>
위와 같은 동작이지만 vue.js-1에서만 동작하는 다른 방법 중 하나를 찾았습니다.vue.js-2에서는 동작하지 않습니다.
var createNewBox = function() {
var MyPartial = Vue.extend({});
window.partial = new MyPartial({
template: '#partial',
data: function() {
return {
txt: 'This is partial'
}
},
methods: {
print: function() {
console.log('this.txt : ' + this.txt)
console.log('main.txt : ' + main.txt)
},
},
})
window.partial.$mount().$appendTo('body')
}
window.main = new Vue({
el: '#main',
data: function() {
return {
txt: 'This is main'
}
},
methods: {
show: function() {
createNewBox()
}
},
})
<script src="https://cdn.bootcss.com/vue/1.0.17/vue.min.js"></script>
<div @click="show" style="width:200px;height:200px;background:#000" id="main">
<template id="partial">
<div style="width:100px;height:100px;background:#ff0" @click.stop="print"></div>
</template>
</div>
이것은 Vue로 변환되었습니다.
https://codepen.io/jacobgoh101/pen/Kojpve
<div id="app">
<div class="parent">
<div class="child" @click="handleChildClick" data-new-child-id="1">1234</div>
<div class="child" @click="handleChildClick" data-new-child-id="2">12341234 </div>
<div class="child" @click="handleChildClick" data-new-child-id="3">123412341234</div>
<div class="child" @click="handleChildClick" data-new-child-id="4">1234</div>
<div class="new-child" v-if="[1,2,3,4].indexOf(showNewChild) > -1">boom</div>
<div class="child" @click="handleChildClick" data-new-child-id="5">12341234</div>
<div class="child" @click="handleChildClick" data-new-child-id="6">123412341234</div>
<div class="child" @click="handleChildClick" data-new-child-id="7">1234</div>
<div class="child" @click="handleChildClick" data-new-child-id="8">12341234</div>
<div class="new-child" v-if="[5,6,7,8].indexOf(showNewChild) > -1">boom</div>
<div class="child" @click="handleChildClick" data-new-child-id="9">123412341234</div>
<div class="new-child" v-if="[9].indexOf(showNewChild) > -1">boom</div>
</div>
</div>
자바스크립트
new Vue({
el: '#app',
data: {
showNewChild:null
},
methods: {
handleChildClick(e) {
let id = e.target.dataset.newChildId;
id = Number(id);
this.showNewChild = id;
}
}
})
언급URL : https://stackoverflow.com/questions/49827347/how-to-add-or-remove-vue-js-component-dynamically-programmatically-or-on-the-fl
'programing' 카테고리의 다른 글
Java RMI와 RPC의 차이점은 무엇입니까? (0) | 2022.08.18 |
---|---|
vue: 구문 오류: wait는 예약된 단어입니다. (0) | 2022.08.18 |
라우터의 getter에서 데이터를 가져올 수 없습니다.[Vux 퀘이사] (0) | 2022.08.18 |
uint와 부호 없는 int의 차이점? (0) | 2022.08.18 |
vuetify: 동적 목록을 사용하는 v-chip v-model (0) | 2022.08.18 |