【问题标题】:How to call a method function in watch vuejs如何在watch vuejs中调用方法函数
【发布时间】:2021-04-22 11:56:14
【问题描述】:

我这样写代码:

<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)
    }
}

我的代码没有结果。有人可以帮我解决我做错了什么吗?

【问题讨论】:

  • 不使用 watch 函数的返回值。这看起来作为计算属性会更好
  • @Phil 我试过用计算但它也没有结果
  • 您的命名似乎有些不一致。是showItem 还是showIndex,这个价值从何而来?
  • edit your question包含代码
  • @phil 好的,我编辑了它

标签: vue.js methods watch


【解决方案1】:

您似乎想根据组合框中的数字显示products 的子集。

正如 cmets 中提到的,这最好通过计算属性来完成

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>

【讨论】:

  • 很多@Phil
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2021-09-30
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多