avatar
fireworks99
keep hungry keep foolish

Vue filters

过滤器的作用:格式化数据。(不修改原数据,只是对数据进行加工,并返回加工后的数据)

1. 应用位置

①. 双花括号插值里

②. v-bind表达式(很少用)

<body>
  <div id="app">
    {{message}}
    <br>
    {{message | capitalize}}
  </div>

  <script src="../js/vue.js"></script>
  <script>
    const app = new Vue({
      el: "#app",
      data: {
        message: "hello world!",
        numString: 500
      },
      filters: {
        capitalize: function(value) {
          if(!value) return "";
          value = value.toString();
          return value.charAt(0).toUpperCase() + value.slice(1);
        }
      }
    })
  </script>
</body>
hello world
Hello world

2. 作用范围

①.全局

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
  // ...
})

②.组件内

filters: {
  capitalize: function (value) {
    if (!value) return ''
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}

Stack Overflow:I’m definitely doing something wrong but after multiples hours of Google, I can’t find why!

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy