我在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
})();
然后在我的虚拟世界里
new Vue.createApp({
data() {
collection: collection
}
}).mount('#app')
发布于 2022-07-16 14:15:54
您使用传统的直接操作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>
https://stackoverflow.com/questions/73004461
复制相似问题