programing

Vue.js의 ''에 있는 텍스트를 참조하는 방법

prostudy 2022. 5. 7. 09:32
반응형

Vue.js의 ''에 있는 텍스트를 참조하는 방법

Vue.js에 있는 텍스트를 참조하는 방법

Vue.component('component', {
  template: `<button><slot></slot></button>`,
  created: function() {
    // i would like to access the text in slot here
  }
});

참고: 이 대답은 Vue v2에만 적용된다.

기본 슬롯 내의 내용(설명하는 내용)은 다음과 같이 노출된다.this.$slots.default부에에서그래서 당신의 단추 안에 있는 텍스트를 얻는 가장 순진한 방법은this.$slots.default[0].text.

Vue.component('component', {
  template: `<button><slot></slot></button>`,
  created: function() {
    const buttonText = this.$slots.default[0].text;
  }
});

문제는 슬롯 내부에 노드가 둘 이상 있을 수 있고, 노드가 반드시 텍스트일 필요는 없다는 점이다.다음 버튼을 고려하십시오.

<button><i class="fa fa-check"></i> OK</button>

이 경우 첫 번째 솔루션을 사용하면undefined왜냐하면 슬롯의 첫 번째 노드는 텍스트 노드가 아니기 때문이다.

이를 수정하기 위해 렌더링 기능에 대한 Vue 설명서의 기능을 빌릴 수 있다.

var getChildrenTextContent = function (children) {
  return children.map(function (node) {
    return node.children
      ? getChildrenTextContent(node.children)
      : node.text
  }).join('')
}

그리고 쓰세요

Vue.component("mybutton", {
  template:"<button><slot></slot></button>",
  created(){
    const text = getChildrenTextContent(this.$slots.default); 
    console.log(text)
  }
})

그러면 슬롯에 있는 모든 텍스트가 함께 연결된다.위의 예를 아이콘과 함께 가정하면, "확인"으로 되돌아온다.

부모에 의해 전달된 슬롯 텍스트를 가져오는 아래 코드 조각 실행:

"ref"를 사용하는 중:

<span ref="mySlot">

this.$refs.mySlot.innerHTML

주의:<slot ref="refName"></slot>때문에 효과가 없다<slot>html로 렌더링되지 않는다.너는 그 일을 끝내야 한다.<slot></slot>와 함께<div></div>또는<span></span>

코드:

Vue.component('component', {
  template: '<button>' +
              '<span ref="mySlot">' +
              
                  'Text before<br />' +
                  
                  '<slot name="slot1">' +
                      'Text by default' +
                  '</slot>' +
                  
                  '<br />Text after' +
                  
              '</span>' +
          '</button>',
  mounted: function() {
    console.log( this.$refs.mySlot.innerHTML);
  }
});

new Vue({
	el: '#app'
});
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="app">
  <component>
    <span slot="slot1">I'm overriding the slot and text appear in this.$refs.mySlot.innerHTML !</span>
  </component>
</div>

Vue 3을 위해서.

@bert의 대답은 Vue 2에서는 잘 통하지만 Vue 3 슬롯은 더 복잡한 구조를 가지고 있다.

슬롯 텍스트 내용을 가져오는 방법(다음에서)defaultVue 3에 슬롯).

const getSlotChildrenText = children => children.map(node => {
  if (!node.children || typeof node.children === 'string') return node.children || ''
  else if (Array.isArray(node.children)) return getSlotChildrenText(node.children)
  else if (node.children.default) return getSlotChildrenText(node.children.default())
}).join('')


const slotTexts = this.$slots.default && getSlotChildrenText(this.$slots.default()) || ''
console.log(slotTexts)

슬롯 안에 있는 모든 어린이의 innerText에 가입하면 슬롯 텍스트에 액세스할 수 있다.

getSlotText() {
  return this.$slots.default.map(vnode => (vnode.text || vnode.elm.innerText)).join('');
},

나의 사용 사례는 매우 간단했다. 나는 텍스트만 있는 기본 슬롯을 가지고 있었다.스크립트 설정을 사용하여 vue3의 텍스트에 액세스하는 방법:

<script setup lang="ts">
import { computed, useSlots } from "vue";

const slots = useSlots();

const slotText = computed(() => {
    return slots.default()[0].children; // This is the interesting line
});
</script>

참조URL: https://stackoverflow.com/questions/42950967/how-to-reference-text-thats-in-slot-slot-in-vue-js

반응형