[英]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 中,我們設置狀態,然后可以由您的模板呈現。
反而:
data
屬性來存儲您的狀態methods
下,編寫一個函數來獲取數據,然后更新組件data
created
的鈎子中調用您的函數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.