首页 > 解决方案 > 未知的自定义元素和指令

问题描述

我(仍在学习 Vue 并且)尝试使用带有产品选择器(Select2 组件)、一些税收计算(方法)和一些输入格式规则(Inputmask)的 Vue2 制作动态表。

一切正常,只有混合的子组件和指令没有按预期工作。

我正在使用 Webpack,所以所有组件/指令都被导入。这是入口JS:

import DecimalMask from './directives/inputmask/decimal-mask';
new Vue({
el: '#vue-app',
components: {
    ....
    'select2-ajax': Select2Ajax,
    'select2-simple': Select2Simple,
    'dynamic-table': DynamicTable,
},
directives: {
    'price-mask': PriceMask,
    'decimal-mask': DecimalMask,
    'date-mask': DateMask,
    ....
}
});

这里我有 DynamicTables 组件。

export default {
    props: {
        tableRows: {
            type: Array,
            default: function(){ return [{}] }
        }
    },
    data: function() {
        return {
            rows: this.tableRows
        }
    },
    computed: {
        total: function () {
            var t = 0;
            $.each(this.rows, function (i, e) {
                t += (e.price * e.qty);
            });
            return t;
        }
    },
    methods: {
        addRow: function () {
            try {
                this.rows.push({});
            } catch (e) {
                console.log(e);
            }
        },
        removeRow: function (index) {
            if(this.rows.length > 1)
                this.rows.splice(index, 1);
        }
    }
};

而这个是 inline-template 部分

...
<tr v-for="(row, index) in rows">
    <td>
        <select2-ajax
                inline-template
                v-model="row.product_id"
                ajax-source="{{ AURL::to('common/product-suggestion') }}">
            <select name="product[]" class="form-control">
            </select>
        </select2-ajax>
    </td>
    <td>
        <input v-decimal-mask class="form-control" name="qty[]" v-model="row.qty" number/>
    </td>
    <td>
        <input v-decimal-mask.price class="form-control text-right" name="price[]" v-model="row.price" number data-type="currency"/>
    </td>
    <td>
        <input v-decimal-mask.price class="form-control text-right" name="total[]" :value="row.qty * row.price" number readonly />
    </td>
    <td>
        <button type="button" class="btn btn-danger col-md-12" @click="removeRow(index)"><i class="fa fa-times"></i></button>
    </td>
</tr>
...

目前我收到以下错误 - 都在 DynamicTables 组件中:

组件和指令都可以在其他地方完美运行(没有混合在其他组件中),但从我的逻辑来看,它们应该在同一个 Vue 实例中存在/存在时工作。谢谢!

标签: javascriptvue.jsvuejs2vue-component

解决方案


您应该在全球范围内注册它们,以便在您的应用程序的任何地方使用它们:

import DecimalMask from './directives/inputmask/decimal-mask';
Vue.directive('decimal-mask',DecimalMask);
....
import customComponent from './Components/customComponent.vue'
Vue.component('custom-component',customComponent);
...
new Vue({...})

推荐阅读