Skip to content

Instantly share code, notes, and snippets.

@jCrip
Forked from TheTrigger/vue-uppercase.js
Created June 12, 2020 17:24
Show Gist options
  • Save jCrip/28e6c3b251966bea03e53ba0ed3f92eb to your computer and use it in GitHub Desktop.
Save jCrip/28e6c3b251966bea03e53ba0ed3f92eb to your computer and use it in GitHub Desktop.
vuejs uppercase directive
Vue.directive("uppercase", {
twoWay: true,
// TODO: unbind
unbind: () => {},
bind: function (el, binding, vnode) {
const findVModelName = vnode => {
try {
// https://forum.vuejs.org/t/solved-how-can-you-update-the-v-model-from-a-custom-directive-in-vue-2/2275
return vnode.data.directives.find(o => {
return o.name === "model";
}).expression;
} catch (error) {
error.message = `Unable to find v-model directive at ${
vnode.tag
} tag. Please specify the expression: v-uppercase='obj.prop'`;
throw error;
}
};
const funcByName = (functionName, context, value) => {
// https://stackoverflow.com/a/359910/8801075
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++)
context = context[namespaces[i]];
return (context[func] = value);
};
var expression = binding.expression ?
binding.expression :
findVModelName(vnode);
vnode.context.$watch(expression, {
//deep: true, // ?
immediate: true,
handler(newVal) {
if (newVal) {
return funcByName(
expression,
vnode.context,
newVal.toString().toLocaleUpperCase()
);
}
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment