IT이야기

VueJs: 구성 요소 내부의 루트 요소에서 방법 사용

cyworld 2022. 4. 12. 00:29
반응형

VueJs: 구성 요소 내부의 루트 요소에서 방법 사용

간단한 HTML 페이지에서는 다음과 같은 vueJs 코드를 사용했다.나는 DOM에 체크박스와 텍스트를 삽입할 버튼을 클릭해야 한다.

내 코드는 다음과 같다.

<template id="add-item-template">
    <div class="input-group">
        <input  v-model="newItem" placeholder="add shopping list item" type="text" class="form-control">
        <span class="input-group-btn">
            <button @click="addItem" class="btn btn-default" type="button">Add!</button>
        </span>
    </div>
</template>

<div id="app" class="container">
    <h2>{{ title }}</h2>
    <add-item-component></add-item-component>
</div>

그리고 자바스크립트 부분은 다음과 같다.

<script>
    var data = {
        items: [
            {
                text: 'Bananas', 
                checked: true 
            }, 
            { 
                text: 'Apples', 
                checked: false 
            }
        ],
        title: 'My Shopping List'
    };

    Vue.component('add-item-component', {
        template: '#add-item-template',
        data: function () {
            return {
                newItem: ''
            }
        },
        props:['addItem']
    });

    new Vue({
        el: '#app',
        data: data,
        methods: {
            addItem: function () {
                var text;

                text = this.newItem.trim();
                if (text) {
                    this.items.push({
                        text: text,
                        checked: false
                    });
                    this.newItem = "";
                }
            }
        }
    });

</script>

페이지를 실행하면 콘솔에서 다음 오류 메시지가 나타난다.

[부유 경고]:이벤트 "클릭"에 대한 잘못된 핸들러: 정의되지 않음(구성 요소에서 발견됨)

나는 그것을 이해한다addItem메서드가 정의되지 않음add-item-template템플릿 등을 사용했지만addItem소품으로서, 클릭 핸들러는 정의되지 않게 된다.

이제 어떻게 하면 클릭 핸들러를 작동시킬 수 있을까?

하위 구성 요소에서 이벤트를 클릭하고 상위 구성 요소에서 출력을 보려면 해당 구성 요소에서 이벤트를 클릭하십시오.emit부모에 대한 사건상위 구성 요소에서 해당 내용을 들을 수 있음emitted event그리고 그걸 처리해라.

var data = {
        items: [{ text: 'Bananas', checked: true }, { text: 'Apples', checked: false }],
        title: 'My Shopping List'
    };

Vue.component('add-item-component', {
    template: '#add-item-template',
    data: function () {
        return {
            newItem: ''
        }
    },
    methods: {
        addItem() {
            const text = this.newItem.trim();
            if(text) {
              // we are emitting an event called "add" and data object {item: this.newItem}
              this.$emit('add', { text });
            }
        }
    }
});



new Vue({
    el: '#app',
    data,
    methods: {
      // here we're handling `add` event from child component with destructured `data` object as a parameter
        addNewItem({text}) {
          data.items.push({
              text,
              checked: false
          });
          console.log(data)
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template id="add-item-template">
        <div class="input-group">
            <input  v-model="newItem" placeholder="add shopping list item" type="text" class="form-control">
            <span class="input-group-btn">
          <button @click="addItem" class="btn btn-default" type="button">Add!</button>
        </span>
        </div>
    </template>

<div id="app" class="container">
    <h2>{{ title }}</h2>
    <!-- here we are listening to the `add` event from the child component -->
    <add-item-component @add="addNewItem"></add-item-component>
    <div v-for="item in items"> {{ item.text }}</div>
</div>

참조URL: https://stackoverflow.com/questions/58909537/vuejs-use-method-from-root-element-inside-a-component

반응형