sourcecode

컴포넌트로 랩된html을 캡처하여 vue.js의 데이터 값을 설정합니다.

copyscript 2022. 9. 3. 13:28
반응형

컴포넌트로 랩된html을 캡처하여 vue.js의 데이터 값을 설정합니다.

나는 팁 기반의 컴포넌트를 만들고 있다.컴포넌트 태그 내에 있는html을 가져오고 싶다.

<vue-wysiwyg>
    <p>Hey, this is some test text.</p>
    <p>I should end up in editor.content</p>
</vue-wysiwyg>

그리고 내 컴포넌트에 대한 editor.content data를 보내달라고 해.

export default {
  data() {
    return {
      editor: new Editor({
        content: '',
      }),
    }
  },
}

슬롯에 대해 생각해 봤는데 html을 통과했을 뿐 캡처가 되지 않습니다.

슬롯에 vdom 객체가 포함되어 있기 때문에 vue를 사용하여 html로 변환해야 합니다.다음 기능이 작동합니다.

computed: {
    html(){

        return new Vue({ 
                render: h => h('div', {}, this.$slots.default)
            })
            .$mount().$el.innerHTML
    } 
}

렌더링 기능만 있는 단순한 컴포넌트 인스턴스를 만듭니다.$mountDOM을 생성하기 위해서입니다.innerHTMLroot 요소에서 추출합니다.

메모: 이 파일의 Vue를 Import해야 합니다.

컴포넌트에 a를 지정할 수 있습니다.ref내부 HTML에 접속하여 할당한다.editor.content

<vue-wysiwyg ref="wysiwyg">
    <p>Hey, this is some test text.</p>
    <p>I should end up in editor.content</p>
</vue-wysiwyg>

그리고 장착된 라이프 사이클 훅은

export default {
  data() {
    return {
      editor: new Editor({
        content: '',
      }),
    }
  },
  mounted() {
    this.editor.content = this.$refs.wysiwyg.$el.innerHTML;
  }
}

이 샌드박스처럼

도움이 되었으면 좋겠다

언급URL : https://stackoverflow.com/questions/58253943/capturing-html-wrapped-by-the-component-to-set-a-data-value-in-vue-js

반응형