Vue过滤器基本使用

1、app.vue 使用methods实现:

<template>
  <div>
    {{ uppercase(message) }}
    <h3>
      <h3 :x="mySlice(msg)">Titleh3>
    h3>
  div>
template>

<script>
export default {
  data() {
    return {
      message: "Hello World",
      time: 1621561377603,
      msg: "你好啊,CSDN!!!",
    };
  },
  methods:{
    mySlice(value) {
      return value.slice(0, 7);
    },
    uppercase(value) {
      return value.toUpperCase();
    }
  }
};
script>

2、使用filters配合computed计算属性实现:

<template>
  <div>
    {{ filteredMessage }}
  div>
template>

<script>
export default {
  data() {
    return {
      message: 'Hello World'
    };
  },
  computed: {
    filteredMessage() {
      return this.$options.filters['myfilter'](this.message);
    }
  },
  filters: {
    myfilter(value) {
      return value.slice(0, 4);
    }
  }
};
script>

3、引入其他组件FilterFix.vue实现:
app.vue

<template>
  <div>
    {{ nself }}
    <FilterFix/>
  div>
template>

<script>
import FilterFix from './components/FilterFix.vue'

export default {
  name: 'App',
  data() {
    return {
      message: "Hello World!!!",
    };
  },
  components: {
    FilterFix,
  },
  computed: {
    nself() {
      return this.$options.filters['myfilter'](this.message);
    },
  },
  filters: {
    myfilter(value) {
      return value.slice(0, 7);
    },
  },
};
script>

FilterFix.vue

<template>
  <div>
    {{ $options.filters.myfilter(message) }}
  div>
template>
  
  <script>
export default {
  name: "filter-fix",
  data() {
    return {
      message: "Hello World!!!",
    };
  },
  filters: {
    myfilter(value) {
      return value.slice(0, 9);
    },
  },
};
script>

main.js

import Vue from 'vue'
import App from './App.vue'
new Vue({
    render: h => h(App)
}).$mount('#app')

你可能感兴趣的:(Vue,前端,vue.js,前端,javascript)