Vue 如何从父级调用过滤器

Pen*_*ers 0 javascript vue.js vue-component vuejs2

我怎样才能使用单个文件组件调用父级过滤器。下面是我的代码。

应用程序.js

import computed from '../vue/mixins/computed.js';
import filters from '../vue/mixins/filters.js';
import methods from '../vue/mixins/methods.js';

const app = new Vue({
    el: '#app',
    mixins:[
        computed,
        filters,
        methods
    ],
    mounted: function() {

    }
});
Run Code Online (Sandbox Code Playgroud)

家.vue

<template>
    <div class="home-content">
        <h3>{{home | uppercase}}</h3>
    </div>
</template>
<script type="text/javascript">
    export default {
        data: function() {
            return {
                home: 'home'
            }
        },
        mounted: function() {
            this.$parent.$options.methods.makeConsole();
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

它在控制台中给我这个警告“无法解析过滤器:大写”

Rei*_*ner 5

  • 您应该在启动根实例之前使过滤器全局可用

    Vue.filter('uppercase', uppercase);
    
    Run Code Online (Sandbox Code Playgroud)

    大写可以是一个简单的函数,如

    function uppercase(str)
      return str.uppercase();
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这将是在所有 vue 组件上使用过滤器的最简单和可靠的方法;

  • 如果您通过 mixin 将过滤器导入您的父级,为什么不在子级中使用该 mixin?

  • 请不要使用this.$parent- 方法,因为它会使您的子组件静态依赖于该父组件。

    • 要使用该$parent方法,您可能需要将父级的过滤器函数声明为子级的过滤器:

      过滤器:{ 大写:this.$parent.$options.filters.uppercase }