如何在watch vuejs中调用方法函数
How to call a method function in watch vuejs
我这样写代码:
<select class="section" @change="showIndex($event.target.selectedIndex)">
<option v-for="number in 50">{{ number}} per page</option>
</select>
<div class="product__layout" v-for="product in showItem">
<p class="product__name">{{ product.name }}</p>
...
data() {
return {
products:[
{ name: 'abc' },
{ name: 'xyz' },
],
}
},
methods:{
showIndex(selectedItem){
return selectedItem
}
},
computed:{
showItem(){
return this.products.slice(0, this.showItem)
}
}
我的代码没有结果。有人可以帮我看看我做错了什么吗?
您似乎想根据组合框中的数字显示 products
的子集。
如评论中所述,最好通过计算 属性
new Vue({
el: "#app",
data: () => ({
products:[
{ name: 'abc' },
{ name: 'xyz' },
],
productCount: 1
}),
computed: {
showProducts: ({ products, productCount }) => products.slice(0, productCount)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<p>
Count:
<!-- use v-model to capture the selection -->
<select v-model="productCount" class="section">
<option v-for="number in 50" :value="number">{{ number }} per page</option>
</select>
</p>
<!-- use the computed property here -->
<div v-for="product in showProducts" class="product__layout" :key="product.name">
<p class="product__name">{{ product.name }}</p>
</div>
</div>
我这样写代码:
<select class="section" @change="showIndex($event.target.selectedIndex)">
<option v-for="number in 50">{{ number}} per page</option>
</select>
<div class="product__layout" v-for="product in showItem">
<p class="product__name">{{ product.name }}</p>
...
data() {
return {
products:[
{ name: 'abc' },
{ name: 'xyz' },
],
}
},
methods:{
showIndex(selectedItem){
return selectedItem
}
},
computed:{
showItem(){
return this.products.slice(0, this.showItem)
}
}
我的代码没有结果。有人可以帮我看看我做错了什么吗?
您似乎想根据组合框中的数字显示 products
的子集。
如评论中所述,最好通过计算 属性
new Vue({
el: "#app",
data: () => ({
products:[
{ name: 'abc' },
{ name: 'xyz' },
],
productCount: 1
}),
computed: {
showProducts: ({ products, productCount }) => products.slice(0, productCount)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<p>
Count:
<!-- use v-model to capture the selection -->
<select v-model="productCount" class="section">
<option v-for="number in 50" :value="number">{{ number }} per page</option>
</select>
</p>
<!-- use the computed property here -->
<div v-for="product in showProducts" class="product__layout" :key="product.name">
<p class="product__name">{{ product.name }}</p>
</div>
</div>