簡體   English   中英

Vue不呈現獲取的html

[英]Vue not rendering fetched html

我在 shopify 中使用 vue 並且正在處理一個集合頁面。 當我單擊過濾器時,它是一個 href,它會更新 url 並重新加載頁面。

所以我有一個產品網格

<div class="grid-wrapper">
  <template v-for="(product, index) in collection.products">
    <div class="product-item"></div>
  </template>
</div>

我的想法是只使用與 fetch 相同的 url,這樣頁面就不會重新加載。

我做了這個

fetch('/collections?variant=black')
  .then(res => res.text())
  .then(html => new DOMParser().parseFromText(html, 'text, html'))
  .then(data => {
    document.querySelector('.grid-wrapper').innerHTML = data.querySelector('.grid-wrapper').innerHTML
  })

這不起作用,因為我取回了實際的<template v-for…>作為新的 innerHTML 並且 vue 沒有接管。 我該如何解決這個問題

在shopify中,我像這樣轉換了對象

const collection = (() => {
  const collection = {{ collection | json }}
  const products = {{ collection.products | json }}
  collection.products = products
  return collection
})();

然后在我的 vue 實例中

new Vue.createApp({
  data() {
    collection: collection
  }
}).mount('#app')

您正在以直接操作 DOM 的傳統 JavaScript 方式處理此問題。 在 Vue 中,我們設置狀態,然后可以由您的模板呈現。

反而:

  1. 創建一個data屬性來存儲您的狀態
  2. methods下,編寫一個函數來獲取數據,然后更新組件data
  3. 在組件created的鈎子中調用您的函數
  4. 在您的template中呈現結果
    • 不要忘記先檢查它是否存在,使用v-if
    • 您可以使用v-for來迭代和渲染列表

這是一個工作演示


我無權訪問您的 API 端點,因此出於演示目的,我只是使用 GitHub API 來獲取和呈現 Vue.js 組織中所有 repos 的列表。

這是它的樣子:

 Vue.config.devtools = false; Vue.config.productionTip = false; new Vue({ el: '#app', name: 'dbzx10299-demo', data() { return { loaded: false, response: null, } }, methods: { fetchData() { const demoEndpoint = 'https://api.github.com/orgs/vuejs/repos'; fetch(demoEndpoint) .then(response => response.json()) .then(data => { this.response = data; this.loaded = true; }) }, }, mounted() { this.fetchData(); }, })
 <script src="https://unpkg.com/vue@2.x/dist/vue.js"></script> <div id="app"> <div class="hello"> <h2>Vue Repo List - Data fetching example</h2> <div v-if="!loaded">Loading...</div> <ul v-else> <li v-for="(repo, index) in response" :key="index"> <a :href="repo.html_url" :title="repo.description" target="_blank"> {{ repo.name }} </a> <i>★ {{ repo.stargazers_count }}</i> </li> </ul> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM