IT이야기

Vue.js에서 .appendChild와 함께 추가된 동적 요소에 v-model 연결

cyworld 2022. 6. 28. 23:26
반응형

Vue.js에서 .appendChild와 함께 추가된 동적 요소에 v-model 연결

Vue.js 래퍼가 없는 라이브러리로 작업하고 있습니다.라이브러리는 동적 방식으로 DOM에 요소를 추가합니다.

저는 이 모든 것을v-modelVue와 함께 이러한 요소들에 기인하며, 한 번 추가된 요소들은 내 모델에서 함께 작동합니다.

Knockout.js와 같은 다른 반응형 프레임워크에서 이 작업을 수행한 적이 있지만 vue.js에서는 이 작업을 수행할 방법을 찾을 수 없습니다.

이렇게 해서 벌이가 되나요?다음 행 중 하나일 것입니다.

var div = document.createElement('div');
div.setAttribute('v-model', '{{demo}}');
[VUE CALL] //tell vue.js I want to use this element in my model.

document.body.appendChild(div);

라이브러리에 대한 래퍼 구성 요소를 만든 다음 사용자 지정 구성 요소를 설정할 수 있습니다.v-model원하는 대로 결과를 얻을 수 있습니다.라이브러리가 DOM 의 조작을 담당하기 때문에, 모델을 최신 상태로 유지하기 위해서 라이브러리에서 제공하는 이벤트에 접속할 필요가 있습니다.당신은 가질 수 있다v-model컴포넌트 지원:

  • 를 받아들입니다.value받침대
  • 이 제품은input이벤트

다음은 비슷한 예를 제시하겠습니다.https://codesandbox.io/s/listjs-jquery-wrapper-sdli1 및 구현한 래퍼 컴포넌트의 스니퍼입니다.

<template>
  <div>
    <div ref="listEl">
      <ul ref="listUlEl" class="list"></ul>
    </div>
    <div class="form">
      <div v-for="variable in variables" :key="variable">
        {{ variable }}
        <input v-model="form[variable]" placeholder="Enter a value">
      </div>
      <button @click="add()">Add</button>
    </div>
  </div>
</template>

<script>
export default {
  props: ["value", "variables", "template"],

  data() {
    return {
      form: {}
    };
  },

  mounted() {
    this.list = new List(
      this.$refs.listEl,
      {
        valueNames: this.variables,
        item: this.template
      },
      this.value
    );

    this.createFormModels();
  },

  methods: {
    createFormModels() {
      for (const variable of this.variables) {
        this.$set(this.form, variable, "");
      }
    },

    add() {
      this.$emit("input", [
        ...this.value,
        {
          id: this.value.slice(-1)[0].id + 1,
          ...this.form
        }
      ]);
    }
  },

  watch: {
    value: {
      deep: true,
      handler() {
        this.$refs.listUlEl.innerHTML = "";

        this.list = new List(
          this.$refs.listEl,
          {
            valueNames: this.variables,
            item: this.template
          },
          this.value
        );
      }
    }
  },

  beforeDestroy() {
    // Do cleanup, eg:
    // this.list.destroy();
  }
};
</script>

요점:

  • 커스텀 라이브러리의 초기화를 다음에 실시합니다.mounted()DOM을 작성하기 위해서입니다.조작할 요소가 필요한 경우,<template>를 붙입니다ref또한 라이브러리 상의 이벤트 청취자를 설정해서 모델 업데이트를 트리거할 수 있습니다.$emit('value', newListOfStuff).
  • watch에 대한 변경에 대해서value라이브러리를 다시 초기화할 수 있도록 하거나 라이브러리의 컬렉션을 업데이트하는 방법을 제공하는 경우 대신 사용하십시오.라이브러리가 이전 인스턴스를 지원하고 이벤트 핸들러를 바인딩 해제하는 경우 이전 인스턴스를 정리해야 합니다.
  • 청소 작업 호출, 이벤트 핸들러 삭제beforeDestroy.

자세한 내용은 다음을 참조하십시오.

언급URL : https://stackoverflow.com/questions/59847450/attach-v-model-to-a-dynamic-element-added-with-appendchild-in-vue-js

반응형