代码之家  ›  专栏  ›  技术社区  ›  panthro

在v-for内使用过滤器?

  •  0
  • panthro  · 技术社区  · 6 年前

    在v-for循环中,如何对文本应用过滤器?我的内联模板:

     <select>
         <option v-for="(item, index) in items" :key="index" :value="item.id" v-text="item.name | capitalize"></option>
    </select>
    

    我收到多个警告 Property or method "capitalize" is not defined on the instance but referenced during render. 即使过滤器已定义。

    所以我想这是循环中的某种范围问题?如何解决这个问题?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Sphinx    6 年前

    Vue Guide: Filters 如前所述,过滤器在 胡须插值 v-bind表达式 ,不包括指令。

    为了你的密码, 解决方案1 胡须插值 .

    Vue.filter('global-capitalize', function (value) {
      return value.toUpperCase()
    })
    
    new Vue({
      el: "#app",
      data: {
        items: [
          { text: "Learn JavaScript", id: 1 },
          { text: "Learn Vue", id: 2 },
          { text: "Play around in JSFiddle", id: 3 },
          { text: "Build something awesome", id: 4 }
        ]
      },
      filters: {
        capitalize: function (name) {
          return name.toUpperCase()
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <h2>Todos:</h2>
      <select>
       <option v-for="(item, index) in items" :key="index" :value="item.id">
       {{item.text | capitalize}}
       </option>
      </select>
      
      <select>
       <option v-for="(item, index) in items" :key="index" :value="item.id">
       {{item.text | global-capitalize}}
       </option>
      </select>
    </div>

    另一个解决方案 is使用计算属性或方法。

    new Vue({
      el: "#app",
      data: {
        items: [
          { text: "Learn JavaScript", id: 1 },
          { text: "Learn Vue", id: 2 },
          { text: "Play around in JSFiddle", id: 3 },
          { text: "Build something awesome", id: 4 }
        ]
      },
      computed: {
        computedItems: function () {
          return this.items.map(item => {
            return {text: item.text.toUpperCase(), id: item.id}
          })
        },
      },
      methods: {
        filterFunc: function (name) {
          return name.toUpperCase()
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <select>
       <option v-for="(item, index) in computedItems" :key="index" :value="item.id" v-text="item.text">
       </option>
      </select>
      
      <select>
       <option v-for="(item, index) in items" :key="index" :value="item.id" v-text="filterFunc(item.text)">
       </option>
      </select>
    </div>