I am creating some custom components based on Element UI.
I have two issues at the moment:
- Pass all the context down from the wrapper to the component;
- When I click on the select element in the following snippet the event does not trigger the change of currentValue. I tried also with #onchange="setValue" :value="currentValue", but nothing changed.
Obviously if I use Select and Option as they come with Element UI, they do work as supposed.
The reason why I need to wrap the components is that I need to add some default classes and brand them with some custom CSS.
---CustomSelect.js
import Vue from 'vue';
import { Select } from 'element-ui';
import classnames from 'classnames';
import 'element-theme-chalk/src/select.scss';
import './select.scss';
export default Vue.component('ExampleSelect', {
functional: true,
render(h, context) {
console.log('ExampleSelect context', context);
function wrappedComponent() {
return Select;
}
function getExtendedClassName() {
return classnames('example-select', {
[context.props.classNames]: context.props.classNames
});
}
return h(
wrappedComponent(),
{
class: getExtendedClassName(),
parent: context.parent && Object.keys(context.parent).length > 0 && context.parent,
data: context.data && Object.keys(context.data).length > 0 && context.data,
props: context.props && Object.keys(context.props).length > 0 && context.props,
injections:
context.injections && Object.keys(context.injections).length > 0 && context.injections,
listeners:
context.listeners && Object.keys(context.listeners).length > 0 ? context.listeners : {}
},
context.children && Object.keys(context.children).length > 0 && context.children
);
}
});
---CustomOption.js
import Vue from 'vue';
import { Option as ExampleOption } from 'element-ui';
import classnames from 'classnames';
import 'element-theme-chalk/src/option.scss';
import './option.scss';
export default Vue.component('ExampleOption', {
functional: true,
render(h, context) {
console.log('ExampleSelect option', context);
function wrappedComponent() {
return ExampleOption;
}
function getExtendedClassName() {
return classnames('example-option', {
[context.props.classNames]: context.props.classNames
});
}
return h(
wrappedComponent(),
{
class: getExtendedClassName(),
parent: context.parent && Object.keys(context.parent).length > 0 && context.parent,
data: context.data && Object.keys(context.data).length > 0 && context.data,
props: context.props && Object.keys(context.props).length > 0 && context.props,
injections:
context.injections && Object.keys(context.injections).length > 0 && context.injections,
listeners:
context.listeners && Object.keys(context.listeners).length > 0 ? context.listeners : {}
},
context.children && Object.keys(context.children).length > 0 && context.children
);
}
});
Thank you in advance for your help.
I solved the issue.
So it looks like the names of the properties in the data object
https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth
Are different from the names of the properties in context:
https://v2.vuejs.org/v2/guide/render-function.html#Functional-Components
Maybe a suggestion for the future is to make them match, or create an utility that maps them allowing to pass them all at once like that.
This is useful in the context of hocs where you want to delegate the main functionality to the received component and you just want to change a few details and make them default.
Therefore, this is the correct return statement:
return h(
wrappedComponent(),
{
class: getExtendedClassName(),
name: 'ExampleInput',
componentName: 'ExampleInput',
props: context.props,
slots: context.slots(),
scopedSlots: context.scopedSlots,
data: context.data,
parent: context.parent,
on: context.listeners,
inject: context.injections,
},
context.children
);
Related
I am new to vue and I have just started using pinia. I wanna delete an item from array but it does not work
here is my store
import {defineStore} from 'pinia'
export interface ObjectDto {
input: string,
}
interface ObjectDtoInterface {
objects: Array<ObjectDto>
}
export const useSearchHistoryStore = defineStore('objectsStore', {
state: (): ObjectDtoInterface => {
return {
objects: [] as ObjectDto[]
}
},
actions: {
add(dto: ObjectDto) {
if (this.objects
.filter(shd => dto.input === shd.input)
.length === 0) {
this.objects.unshift(dto)
}
},
delete(obj: ObjectDto) {
this.objects = this.objects.filter(e => !(e.input === obj.input))
}
}
})
and here is the function from different .ts file
function delete(obj: ObjectDto) {
objectsStore.delete(obj)
}
add action works perfect, it adds item to the state but when I try to delete an item, nothing happens. The data I pass to delete method is 100% good because I checked this many times
Filter does not mutate the original object, you need to reasing
delete(obj: ObjectDto) {
this.objects = this.objects.filter(e => !(e.input === obj.input))
}
more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
I have this code that works but outputs an error
this.hideButton is not a function
here a part of the code
<template>
<div>
<v-select
#open="openSelect"
#search="applySearch"
>
<b-button variant="none" class="selectAllButton"
v-on:click="clickSelectAll" v-show="hiddenBtn">Select All</b-button>
</div>
</template>
export default {
data() {
return {
hiddenBtn: false
}
},
methods: {
applySearch(search, loading) {
if (search.length > 0 && search.length < 3) {
this.hideBtn();
return;
}
this.showBtn();
this.retrieveEntities(search, loading)
},
showBtn() {
this.hiddenBtn = true;
},
hideBtn(){
this.hiddenBtn = false;
}
}
I think this is the wrong way to update my hiddenBtn property to show and hide the button, but It works even if I get an error, so I don't understand what happens
you are calling this.hideBtn() which is not a function
applySearch(search, loading) {
if (search.length > 0 && search.length < 3) {
this.hideBtn(); // <-- you are calling this.hideBtn() which isn't a function. just remove this and try
return;
}
this.showBtn();
this.retrieveEntities(search, loading)
}
This code should work properly, maybe you have somewhere else in code something that is trying to execute this.hideButton() while your method's name is this.hideBtn().
I'm using this text editor https://github.com/davidroyer/vue2-editor that is based on Quilljs
I want to handle the paste event so it pastes only the plain text without any format but seems in the documentation that paste is not a supported event by default.
Is there any way to add the paste event?
I've already tried using v-on:paste in the Editor and adding the Quill custom module Clipboard but haven't had any success.
As I didn't find a way of doing it with the library I did it with the DOM
onPaste() {
const x = document.getElementById("removePasteFormat");
console.log(x);
x.addEventListener("paste", (e) => {
e.stopPropagation();
e.preventDefault();
let text = e.clipboardData.getData("text/plain");
// access the clipboard using the api
if (document.queryCommandSupported("insertText")) {
document.execCommand("insertText", false, text);
} else {
document.execCommand("paste", false, text);
}
});
},
Added the id to the div containing the text editors like this:
<div id="removePasteFormat"> *<<Here goes the text editor component>>* </div>
And register the method on mounted()
mounted() {
this.onPaste();
},
I think it would be good to make a plugin.
I made it simple.
src/utils/vue2Plugin/clipboard.ts
import Delta from 'quill/node_modules/quill-delta';
import Clipboard from 'quill/modules/clipboard';
import { Quill } from 'vue2-editor';
export class CustomClipboardPlugin extends Clipboard {
public quill!: Quill;
public options: any = {};
constructor(quill: Quill) {
super(quill, {
matchers: [],
});
this.quill = quill;
this.quill.root.addEventListener('paste', this.onPaste.bind(this), true);
}
onPaste(event: ClipboardEvent) {
event.preventDefault();
event.stopPropagation();
const range = this.quill.getSelection(true);
if (range === null) return;
let _textHtml;
if (event.clipboardData?.getData('text/html')) {
_textHtml = event.clipboardData?.getData('text/html');
} else if (event.clipboardData?.getData('text/plain')) {
_textHtml = `<p>${event.clipboardData?.getData('text/plain')}</p>`;
}
if (_textHtml) {
const pastedDelta = this.quill.clipboard.convert(_textHtml);
const delta = new Delta()
.retain(range.index)
.delete(range.length)
.concat(pastedDelta);
this.quill.updateContents(delta, Quill.sources.USER);
this.quill.setSelection(delta.length() - range.length, 0, Quill.sources.SILENT);
}
}
}
vue file
<template>
...
<VueEditor
...
:custom-modules="customModulesForEditor"
...
/>
...
</template>
// script
import CustomClipboardPlugin fro 'src/utils/vue2Plugin/clipboard.ts';
...
data() {
return {
customModulesForEditor: [{ alias: 'clipboard', module: CustomClipboardPlugin }],
};
},
...
I was wondering the same and came up with the following solution.
1 - Use the :editorOptions option referenced here
<template>
VueEditor(:editorOptions="editorSettings")
</template>
2 - Fill with the module.clipboard module with the option described here
3 - You can then handle the paste with your personal function (applied after quill's matcher). I've written mine following this answer on github
<script>
data() {
return {
editorSettings: {
modules: {
clipboard: {
matchers: [[Node.ELEMENT_NODE, this.customQuillClipboardMatcher]]
}
}
}
}
},
methods: {
customQuillClipboardMatcher(node, delta) {
delta.ops = delta.ops.map((op) => {
return {
insert: op.insert
}
})
return delta
},
}
</script>
I want this select multiple to pre-select one option, and not be able to deselect all options.
Whenever the last selected option is deselected it should be reselected. In other words when the user tries to deselect the last selected option it should visually not be deselected.
<template>
<b-select
if="Object.keys(doc).length !== 0 /* wait until firebase has loaded */"
:options="computedOptions"
v-model="model"
multiple
#input="onChange"
/>
</template>
<script>
//import Vue from 'vue'
import { fb } from "../fbconf";
export default {
name: "MyMultiSelect",
props: {
doc: Object, // firestore document
},
data() {
return {
options: []
};
},
firestore() {
var options = fb.db.collection("options");
return {
options: options
};
},
computed: {
computedOptions: function() {
return this.options.map(function(option) {
return {
text: option.name,
value: option.id
};
});
},
// to make sure mySelectedOptions is an array, before this.doc is loaded
// I use the following custom model
// because not using 'get' below causes a warning:
// [Vue warn]: <select multiple v-model="localValue"> expects an Array value for its binding, but got Undefined
model: {
get: function() {
if (!this.doc.hasOwnProperty('mySelectedOptions')) return []; // empty array before this.doc is loaded
else return this.doc['mySelectedOptions'];
},
set: function(newValue) {
// here I can prevent the empty array from being stored
// but visually the user can deselect all options, which is bad UX
//if (Array.isArray(newValue) && newValue.length > 0) this.doc['mySelectedOptions'] = newValue;
}
},
},
methods: {
onChange: function(newValue){
// I can manually store the array as I want here
// but I cannot in any way prevent the user from deselecting all options
if (Array.isArray(newValue) && newValue.length > 0) this.doc['mySelectedOptions'] = newValue;
else {
// none of these reselects the last selected option
var oldValue = this.doc['mySelectedOptions'];
this.doc['mySelectedOptions'] = this.doc['mySelectedOptions'];
//this.$forceUpdate();
//this.$emit("change", newValue);
//Vue.set(this.doc, 'mySelectedOptions', this.doc['mySelectedOptions']);
}
}
}
};
</script>
You could add watcher and when length becomes 0 just add previous value.
watch: {
model(val, oldVal) {
if(val.length == 0 && oldVal.length > 0) {
// take only one item in case there's clear button or etc.
this.model = [oldval[0]];
}
}
}
I have created a Vue component call imageUpload and pass property as v-model
<image-upload v-model="form.image"></image-upload>
and within imgeUpload component
I have this code
<input type="file" accept="images/*" class="file-input" #change="upload">
upload:(e)=>{
const files = e.target.files;
if(files && files.length > 0){
console.log(files[0])
this.$emit('input',files[0])
}
}
and I received
Uncaught TypeError: _this.$emit is not a function
Thanks
Do not define your method with a fat arrow. Use:
upload: function(e){
const files = e.target.files;
if(files && files.length > 0){
console.log(files[0])
this.$emit('input',files[0])
}
}
When you define your method with a fat arrow, you capture the lexical scope, which means this will be pointing to the containing scope (often window, or undefined), and not Vue.
This error surfaces if $emit is not on the current context/reference of this, perhaps when you're in the then or catch methods of a promise. In that case, capture a reference to this outside of the promise to then use so the call to $emit is successful.
<script type="text/javascript">
var Actions = Vue.component('action-history-component', {
template: '#action-history-component',
props: ['accrual'],
methods: {
deleteAction: function(accrualActionId) {
var self = this;
axios.post('/graphql',
{
query:
"mutation($accrualId: ID!, $accrualActionId: String!) { deleteAccrualAction(accrualId: $accrualId, accrualActionId: $accrualActionId) { accrualId accrualRate name startingDate lastModified hourlyRate isHeart isArchived minHours maxHours rows { rowId currentAccrual accrualDate hoursUsed actions { actionDate amount note dateCreated } } actions {accrualActionId accrualAction actionDate amount note dateCreated }} }",
variables: {
accrualId: this.accrual.accrualId,
accrualActionId: accrualActionId
}
}).then(function(res) {
if (res.data.errors) {
console.log(res);
alert('errors');
} else {
self.$emit('accrualUpdated', res.data.data.deleteAccrualAction);
}
}).catch(function(err) {
console.log(err);
});
}
}
});
You can write the method in short using upload(e) { instead of upload:(e)=>{ to make this point to the component.
Here is the full example
watch: {
upload(e) {
const files = e.target.files;
if(files && files.length > 0) {
console.log(files[0]);
this.$emit('input',files[0]);
}
}
}