programing

점진적인 향상을 위해 Vuejs 사용 - 기존 HTML 구문 분석

prostudy 2022. 4. 14. 20:42
반응형

점진적인 향상을 위해 Vuejs 사용 - 기존 HTML 구문 분석

나는 Vue (v2)를 사용하여 HTML 페이지의 일부를 관리하고 싶지만, 사용자가 javscript를 가지고 있지 않더라도 여전히 좋은 페이지를 얻을 수 있도록 그렇게 하고 싶다.

예: 서버가 다음을 출력할 수 있음:

<div id="rootAppContainer">
  ...
  <article is="foo" >
     <h1>Something cool</h1>
     <p>Here's a great article.</p>
  </article>
  ...
</div>

폴백처럼 괜찮지하지만 나는 Vue가 그 기사를 싣고 더 좋은 것으로 대체했으면 좋겠어, 예를 들면.

<article>
   <p v-show="showTeaser" >{{teaser}}</p>
   <div v-show="!showTeaser" >
      <h1>{{title}}</h1>
      <p>Here you go:</p>
      <p>{{body}}</p>
   </div>
</article>

이를 위해 탑재되는 요소의 사전 뷔 콘텐츠를 구문 분석하여 뷰-모델의 콘텐츠를 추출할 수 있기를 바란다.data템플릿에 의해 포맷될 것이다.

라이프사이클 후크나 구성요소의 데이터 방법으로 이것을 할 수 있다고 생각했지만, 너무 늦기 전까지는, 곧 장착될 노드에 대한 참조를 얻을 수 있는 방법을 찾을 수 없다.mounted이미 교체된 경우.

https://codepen.io/artfulrobot/pen/GOGBWQ?editors=1010

먼저 서버측 렌더링에 대해 알아보라고 해야겠습니다.

그러나 SSR 없이 고착된 경우 Vue가 생성되기 전에 DOM을 구문 분석할 수 있으며, 문서를 구성 요소로 교체할 수 있다.

여기 예가 있다.

console.clear()

let root = document.querySelector("#rootAppContainer")
for (let article of root.querySelectorAll('article')){
  let title = article.querySelector("h1").textContent
  let body = article.querySelector("p").textContent
  let foo = document.createElement("foo")
  foo.setAttribute("title", title)
  foo.setAttribute("body", body)
  root.replaceChild(foo, article)
}

const app = new Vue({
  el: '#rootAppContainer',
  components: {
    foo: {
      props:["title", "body"],
      data: function() {
        return {
          showTeaser: true,
        };
      },
      computed: {
        teaser: function() {
          return "ooh, you won't believe this..." + this.title;
        }
      },
      template: `
        <article>
           <p v-show="showTeaser" >{{teaser}}</p>
           <div v-show="!showTeaser" >
              <h1>{{title}}</h1>
              <p>Here you go:</p>
              <p>{{body}}</p>
           </div>
        </article>
      `,
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="rootAppContainer">
  <h2>some content before articles</h2>
  <article>
    <h1>Something cool</h1>
    <p>Here's a great article.</p>
  </article>
  <h2>some content between articles</h2>
  <article>
    <h1>Another cool thing</h1>
    <p>Here's a great article.</p>
  </article>
  <article>
    <h1>And lastly something cool</h1>
    <p>Here's a great article.</p>
  </article>
  <h2>some content after articles</h2>

</div>

참조URL: https://stackoverflow.com/questions/47476665/use-vuejs-for-progressive-enhancement-parse-existing-html

반응형