有没有办法将Vue自定义指令实现为单独的文件(即Vue组件.vue文件),并在根js文件中进行编译?(我用的是Webpack)
我在app.js上尝试了下面的命令,但是它不被识别。
require('./directives/test.js');提前谢谢。
发布于 2017-08-01 03:50:19
指令只是一个包含几个定义良好的方法的类。在JS中,您可以编写如下内容:
export const MyDirective {
bind(el,binding,vnode) {
/* your code */
}
}然后,在使用它的文件中:
<template>
<p v-app-my-directive:arg.modifier="value">Some Text</p>
</template>
<script>
import MyDirective from './directives/MyDirective.js';
export default {
directives: {
AppMyDirective: MyDirective
}
/* ... */
}
</script>您还可以使用
Vue.directive('app-my-directive', MyDirective)全局声明它。
发布于 2018-11-03 15:40:19
您可以创建与创建全局筛选器类似的全局指令文件。
Create a directives.js
import Vue from 'vue'
Vue.directive('purple', function(el) {
el.style.color = 'purple'
})
Import it into your main.js发布于 2019-02-27 23:08:53
我在/js/directives下创建了一个目录,并添加了一个名为AutoFocus.js的文件,其中包含以下内容:
import Vue from 'vue';
const AutoFocus = {
inserted(el) {
el.focus();
},
};
export default {
AutoFocus,
};
// Make it available globally.
Vue.directive('focus', AutoFocus);请注意,您可能需要尝试'bind‘或'update’,而不是上面的'inserted‘,这取决于您的场景的适当钩子函数。我只是替换并测试了每一个,直到其中一个工作了!然后,在我的组件中,我使用如下指令:
<template>
<input type="text" v-focus />
</template>
<script>
import AutoFocus from '../../../directives/AutoFocus'; // Must point to your file!
export default {
directives: {
AutoFocus,
},
// ... your other code here, eg props/methods etc
}
</script>https://stackoverflow.com/questions/42139177
复制相似问题