Error in implementing Vue multiselect properly - vue.js

I am trying to build a dropdown using vue-multiselect, where I am facing an issue. Upon selecting the first option, it works fine. However, when I try to select another option, the earlier selected option also disappears. Given below is the code which I am using:
<template>
<div>
<app-header></app-header>
<multiselect v-model="value" tag-placeholder="Add this as new tag" placeholder="Search or add a tag" label="name" track-by="code" :options="options.campaign_name" :multiple="true" :taggable="true" #tag="addTag1" style="width:200px"></multiselect>
<app-footer></app-footer>
</div>
</template>
<script>
import Header from './components/header.vue'
import Multiselect from 'vue-multiselect'
import Footer from './components/footer.vue'
export default {
components: {
'app-header': Header,
'app-footer': Footer,
'multiselect': Multiselect
},
data() {
return {
value: [
{ name: 'chess', code: 'js' }
],
options:{
campaign_name:[{name:"Chess", code:"js"},{name: "Badminton",code:"js"}],
vmw_platform_test:[],
release_version:[]
},
}
},
methods: {
addTag1 (newTag) {
const tag = {
name: newTag,
code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.options.campaign_name.push(tag)
this.value.campaign_name.push(tag)
}
}
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
<style scoped>
</style>
I guess it must have something to do with the way I am passing the data, but this is actually how I need data to be passed, in order to learn the behavior of a bigger project. Any help is appreciated.
EDIT 1: Upon selecting one component, I am not getting the option to add more options. Instead I am getting the option of only removing it, on all the options.

In your example, you have two options with same code value, and you have set the code property to be tracked as the key that will be pushed into the value array of selected options. Try changing this:
campaign_name:[{name:"Chess", code:"chess"},{name: "Badminton",code:"badminton"}],
As per the docs (https://vue-multiselect.js.org/):
track-by is used to identify the option within the options list thus it’s value has to be unique. In this example the name property is unique across all options, so it can be used as track-by value.

Related

What's the most idomatic Vue way of handling this higher-order component?

I have a VueJS organization and architecture question. I have a bunch of pages that serve as CRUD pages for individual objects in my system. They share a lot of code . I've abstracted this away in a shared component but I don't love what I did and I'm looking for advice on the idiomatic Vue way to do this.
I'm trying to create a higher order component that accepts two arguments:
An edit component that is the editable view of each object. So you can think of it as a stand in for a text input with a v-model accept that it has tons of different inputs.
A list component which displays a list of all the objects for that type in the system. It controls navigation to edit that object.
Normally this would be simply something where I use slots and invoke this component in the view page for each CRUD object. So basically I'd have something like this:
<!-- this file is src/views/DogsCRUDPage.vue -->
<template>
<general-crud-component
name="dogs"
backendurl="/dogs/"
>
<template slot="list">
<dogs-list-component />
</template>
<template slot="edit">
<dogs-edit-field v-model="... oops .." />
</template>
</general-crud-component>
</template>
<script>
export default {
name: "DogCRUDPage",
components: {
GeneralCrudComponent,
DogListComponent,
DogEditField,
},
}
</script>
This is nice because it matches the general syntax of all of my other VueJS pages and how I pass props and things to shared code. However, the problem is that GeneralCRUDComponent handles all of the mechanisms for checking if an object is edited, and therefor hiding or unhiding the save button, etc. Therefor it has the editable object in its data which will become the v-model for DogsEditField or any other that's passed to it. So it needs to pass this component a prop. So what I've done this:
// This file is src/utils/crud.js
import Vue from "vue"
const crudView = (listComponent, editComponent) => {
return Vue.component('CrudView', {
template: `
<v-row>
<list-component />
<v-form>
<edit-component v-model="obj" />
</v-form>
</v-row>
`,
components: {
ListComponent: listComponent,
EditComponent: editComponent,
},
data() {
return {
obj: {},
}
},
})
}
export default crudView
This file has a ton of shared code not shown that is doing the nuts and bolts of editing, undo, saving, etc.
And then in my src/router/index.js
//import DogCRUDPage from "#/views/libs/DogCRUDPage"
import crudView from "#/utils/crud"
import DogListComponent from "#/components/DogListComponent"
import DogEditField from "#/components/design/DogEditField"
const DogCRUDPage = crudView(DesignBasisList, DesignBasis)
Vue.use(VueRouter);
export default new VueRouter({
routes: [
{
path: "/dog",
name: "dog",
component: DogCRUDPage,
},
})
This is working, but there are issues I don't love about it. For one, I needed to enable runtimecompiler for my project which increases the size of the payload to the browser. I need to import the list and edit components to my router instead of just the page for every single object I have a page for. The syntax for this new shared component is totally different from the template syntax all the other pages use. It puts all of my page creation into the router/index.js file instead of just layed out as files in src/views which I am used to in Vue.
What is the idiomatic way to accomplish this? Am I on the right track here? I'm happy to do this, it's working, if this really is how we do this in Vue. But I would love to explore alternatives if the Vue community does something differently. I guess I'm mostly looking for the idiomatic Vue way to accomplish this. Thanks a bunch.
How about this:
DogsPage.vue
<template>
<CrudView
:editComponent="DogsEdit"
:listComponent="DogsList"
></CrudView>
</template>
<script>
import DogsEdit from '#/components/DogsEdit.vue'
import DogsList from '#/components/DogsList.vue'
import CrudView from '#/components/CrudView.vue'
export default {
components: { CrudView },
data() {
return { DogsEdit, DogsList }
}
}
</script>
CrudView.vue
<template>
<div>
<component :is="listComponent"></component>
<component :is="editComponent" v-model="obj"></component>
</div>
</template>
<script>
export default {
props: {
editComponent: Object,
listComponent: Object
},
data() {
return {
obj: {}
}
}
}
</script>

v-select component not loading into HTML

I am trying to create a basic site, where I need to select options from a dropdown menu. I am using the Select.vue from the vue-strap library to implement the same. However, the v-select component in not loading onto the html. Given below is the App.vue which inherits Select.vue from vue-strap:
<template>
<div>
<app-header></app-header>
<v-select v-model="selected" :options="['Vue.js','React']"></v-select>
<app-footer></app-footer>
</div>
</template>
<script>
import Header from './components/header.vue'
import select from '../node_modules/vue-strap/src/Select.vue'
import Footer from './components/footer.vue'
export default {
components: {
'app-header': Header,
'app-footer': Footer,
'v-select': select,
},
data() {
return {
}
},
}
</script>
<style scoped>
</style>
Given below are the errors that I am getting onto the web console:
I am unable to resolve these errors. Any help is appreciated.
:options="['Vue.js','React']"
Above line can be a big problem, since you are passing the static data and not assigning any variable you don't have to use :
: this actually a binding operator you should only use this when you are binding option to some variable
For eg:
data(){
return{
options:[['Vue.js','React']]
}
}
now inside your vue file, you can add
<v-select v-model="selected" :options=options></v-select>
If you dont want to declare variable then you can remove :
<v-select v-model="selected" options="['Vue.js','React']"></v-select>
Always make sure whatever you are passing to the component is declared inside the data
If you want to use computed make sure you declare it upfront before using it

Use Data Variable as Vue Template Without Parent Wrapper

I am trying to embed a Codemirror instance as a Vue component, similar to what was accomplished in this project. However, instead of returning a template of the Codemirror instance inside of a parent
<div class="vue-codemirror" :class="{ merge }">
<!-- Textarea will be replaced by Codemirror instance. -->
<textarea ref="textarea" :name="name" :placeholder="placeholder" v-else>
</textarea>
</div>
I am simplying trying to return the Codemirror instance alone. The reason why I can't simply remove the parent div and have
<!-- Textarea will be replaced by Codemirror instance. -->
<textarea ref="textarea" :name="name" :placeholder="placeholder" v-else>
</textarea>
is because the method to replace the textarea, CodeMirror.fromTextArea(), requires the textarea to have a parentNode. Otherwise, a null error will be encountered.
Luckily, there is a way to create a Codemirror instance without using a textarea at all, CodeMirror(). This instance has a function getWrapperElement() that returns the DOM node:
<div class="CodeMirror cm-s-default">
...
</div>
I want to output this specific DOM node relating to Codemirror instance using the Vue template/render function. The current way I'm creating the instance is by initializing it in the component data object.
data: function () {
// Create a CodeMirror instance.
let cm = new CodeMirror(null, {
...
})
return {
// Define a CodeMirror instance for each CodeBlockView.
cm : cm,
...
}
},
Update 1: I have found one way to do this, albeit very hacker-ish. We use the createElement function that is passed in with render and pass into the data object argument the innerHTML of DOM node we want to render. It seems to be working visually but the CodeMirror instance isn't editable.
render: function (createElement) {
return createElement('div', {
class: this.dom.classList.value,
domProps: {innerHTML: this.dom.innerHTML}
})
}
Update 2: However, this doesn't pass in the actual DOM node rather it only shallowly copies it; this presents a problem as it doesn't allow it to be editable nor have a CodeMirror instance attached.
You cannot change the template anymore after the component has been created. It's not a property of the component but a parameter that is passed to the constructor as far as I know.
Hence, you would need to create the CodeMirror instance before the component is created and inject it.
However, I fail to see the problem with a wrapping component, could you explain the why?
I test many ways and the most simple template I find was keeping the textarea, after that the component should receive options and value and emit the new value.
you can test the component here
I'm not a codeMirror expert, I import many things for keep the codemirror component more flexible, you can adjust the imports with your needs.
//component codeMirror.vue
<template>
<textarea ref="myCm"></textarea>
</template>
<script>
import CodeMirror from 'codemirror';
// language
import 'codemirror/mode/javascript/javascript';
// theme css
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/monokai.css';
// require active-line.js
import 'codemirror/addon/selection/active-line';
// styleSelectedText
import 'codemirror/addon/selection/mark-selection';
import 'codemirror/addon/search/searchcursor';
// hint
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/javascript-hint';
// highlightSelectionMatches
import 'codemirror/addon/scroll/annotatescrollbar';
import 'codemirror/addon/search/matchesonscrollbar';
import 'codemirror/addon/search/match-highlighter';
// keyMap
import 'codemirror/mode/clike/clike';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/comment/comment';
import 'codemirror/addon/dialog/dialog';
import 'codemirror/addon/dialog/dialog.css';
import 'codemirror/addon/search/search';
import 'codemirror/keymap/sublime';
// foldGutter
import 'codemirror/addon/fold/foldgutter.css';
import 'codemirror/addon/fold/brace-fold';
import 'codemirror/addon/fold/comment-fold';
import 'codemirror/addon/fold/foldcode';
import 'codemirror/addon/fold/foldgutter';
import 'codemirror/addon/fold/indent-fold';
import 'codemirror/addon/fold/markdown-fold';
import 'codemirror/addon/fold/xml-fold';
export default {
name: 'codeMirror',
props: {
value: String, // give to the component a start value
options: Object, // give the codeMirror options
},
mounted() {
const myCodemirror = new CodeMirror.fromTextArea(this.$refs.myCm, this.options);
myCodemirror.setValue(this.value);
myCodemirror.on('change', (cm) => {
if (this.$emit) {
this.$emit('input', cm.getValue());
}
});
},
};
</script>
after that is easy to use this component for render codeMirror in multiple instances, readOnly, recovery de data, multiple templates, no limits. ex:
<template>
<div>
Read Only, default theme, value multiple line
<codeMirror :value="value0" :options="noChanges"></codeMirror>
Value Dynamic, theme monokai, other extra fancy things
<codeMirror :value="value" :options="monokai" #input="onCmCodeChange"></codeMirror>
Only for debug, shows the modifications made inside codemirror
{{ value }}
</div>
</template>
<script>
// # is an alias to /src
import codeMirror from '#/components/codeMirror.vue';
export default {
name: 'pageEditor',
components: {
codeMirror,
},
data() {
return {
value0: `let choco: "bombon";
let type: 'caramel;
choco + ' ' + type;`,
value: 'let frankie= "It\'s alive"',
noChanges: {
theme: 'default',
readOnly: true,
tabSize: 2,
line: true,
lineNumbers: true,
},
monokai: {
tabSize: 2,
styleActiveLine: true,
lineNumbers: true,
line: true,
foldGutter: true,
styleSelectedText: true,
mode: 'text/javascript',
keyMap: 'sublime',
matchBrackets: true,
showCursorWhenSelecting: true,
theme: 'monokai',
extraKeys: { Ctrl: 'autocomplete' },
hintOptions: {
completeSingle: false,
},
},
};
},
methods: {
onCmCodeChange(newValue) {
this.value = newValue;
},
},
};
</script>
I hope this help

Setting props of child component in vue

I'm following the example here of using a Vue template as a Kendo UI template in their components:
https://www.telerik.com/kendo-vue-ui/components/framework/vue-templates/
The example isn't very clear on how to supply properties to components that are rendered with this method (as opposed to rendering right in the template). I need to supply a single value determined in the parent to all instances of this child component, and I also need to subscribe to emitted events from the child component. My assumption is that there's an overload to Vue.component() that lets me access this functionality?
Edit:
Specifically what I am looking for is a way to have a header template for each column created from a Vue component. I need each column's template to receive data from the parent so I know how to construct it, and I also need each column's template to report an event back to the parent.
I think the key point is Step 3 in the link you attached (Kendo Vue Template Usage). (Never touch Kendo Before, if anything wrong, correct me, thanks.)
First, please open this Vue kendo Sandbox, you will find one dropdownlist then each option is one button plus one text. If you click the button, it will call one method in MyTemplate.vue and another Method at DropDownStyle.vue, then its background of each option is blue which passed from DropDownStyle.vue.
Kendo will bind this function of Step 3 to its attribute=template, then fisrt parameter (and only one) is each element of the data-source.
Then this function need to return one object including template and templateArgs, then Kendo construct it.
So my solution is add your function/callback/styles into templateArgs, then do what you need at MyTemplate.vue.
Below is the codes extended from Step 3.
methods: {
getMyTemplate: function (e) {
// parameter=e: it is the value of each element of the dropdown
e.callback = this.eventCallback
e.styles="background-color:blue"
return {
template: MyTemplate,
templateArgs: e
}
},
eventCallback: function (data) {
console.log(this.dropdowns)
}
}
Below is MyTemplate.vue.
<template>
<span :style="templateArgs.styles">
<button #click="buttonClick();templateArgs.callback()">{{templateArgs.value}}</button>
{{templateArgs.text}}
</span>
</template>
<script>
export default {
name: 'template1',
methods: {
buttonClick: function (e) {
console.log('props',this.templateArgs.styles)
}
},
data () {
return {
templateArgs: {
callback:function(){
console.log('Test')
},
styles:''
}
}
}
}
</script>
Very odd design choice in terms of passing the template in like they do. Avoiding the KendoUI and focusing on VueJS methods - could you use provide/inject? Providing the value in the parent and injecting in any of the children?
Also a plugin could be created to keep track of events or values you want available to all components in the application. In essence the plugin would be a service. A singleton object that is only instantiated once.
The documentation is indeed lacking. I agree with you on that. I took a different approach with templating for Kendo UI component and got this working: https://codesandbox.io/s/github/ariellephan/vue-kendoui-template
To start, I have this dropdown component that utilizes Kendo dropdown list component:
<template>
<div>
<p>Style with template {{template}}</p>
<kendo-dropdownlist
:template="template"
:headerTemplate="headerTemplate"
:data-source="dataSourceArray"
:data-text-field="'text'"
:data-value-field="'value'"
:filter="'contains'">
</kendo-dropdownlist>
</div>
</template>
<script>
export default {
name: "Dropdown",
props: ["dataSourceArray", "template", "headerTemplate"],
data() {
return {
value: "Click Me",
text: "I'm in Template template"
};
}
};
</script>
To render different styles/templates, I parsed in props from the parent component. In this case, DropdownStyles
<template>
<div id="DropdownStyles">
<h1>KendoUI dropdown instances with different templates</h1>
<Dropdown
v-for="dropdown in dropdowns"
v-bind:key="dropdown.id"
v-bind:title="dropdown.title"
v-bind:data-source-array="dropdown.dataSourceArray"
v-bind:template="dropdown.template"
v-bind:headerTemplate="dropdown.headerTemplate"
></Dropdown>
</div>
</template>
<script>
import Dropdown from "./Dropdown";
import DropdownTemplate from "./DropdownTemplate";
export default {
name: "DropdownStyles",
components: { Dropdown },
data() {
return {
dropdowns: [
{
id: 1,
title: "x style",
dataSourceArray: [
"Football",
"Tennis",
"Basketball",
"Baseball",
"Cricket",
"Field Hockey",
"Volleyball"
],
template: `<strong class="custom-dropdown">x #:data#</strong>`,
headerTemplate: DropdownTemplate.template
},
{
id: 2,
title: "+ style",
dataSourceArray: [
"Football",
"Tennis",
"Basketball",
"Baseball",
"Cricket",
"Field Hockey",
"Volleyball"
],
template: `<strong class="custom-dropdown">+ #:data#</strong>`,
headerTemplate: `<div><h3 style="padding-left:10px;">Sports 2</h3></div>`
}
]
};
}
};
</script>
You can move the template into its own file or function. For example, the first drop down is using DropdownTemplate for its headerTemplate:
DropdownTemplate.vue
<script>
export default {
name: "DropdownTemplate",
props: ["header"],
template: `<div>
<div><h3>Sports 1</h3></div>
</div>`,
data() {
return {};
}
};
</script>
<style scoped>
h3 {
padding-left: 10px;
}
</style>

Determining if slot content is null or empty

I have a little Loading component, whose default text I want to be 'Loading...'. Good candidate for slots, so I have something like this as my template:
<p class="loading"><i class="fa fa-spinner fa-spin"></i><slot>Loading...</slot></p>
That allows me to change the loading message with e.g. <loading>Searching...</loading>. The behaviour I would like, though, is not just to display the default message if no slot content is supplied, but also if the slot content is null or blank. At the moment if I do e.g.<loading>{{loadingMessage}}</loading> and loadingMessage is null, no text is displayed (where I want the default text to be displayed). So ideally I need to test this.$slots.default. This tells me whether content was passed in, but how do I find whether or not it was empty? this.$slots.default.text returns undefined.
You'd need a computed property which checks for this.$slots. With a default slot you'd check this.$slots.default, and with a named slot just replace default with the slot name.
computed: {
slotPassed() {
return !!this.$slots.default[0].text.length
}
}
And then use it in your template:
<template>
<div>
<slot v-if="slotPassed">Loading...</slot>
<p v-else>Searching...</p>
</div>
</template>
You can see a small example here. Notice how fallback content is displayed and not "default content", which is inside the slot.
Edit:
My wording could've been better. What you need to do is check for $slots.X value, but computed property is a way to check that. You could also just write the slot check in your template:
<template>
<div>
<slot v-if="!!$slots.default[0].text">Loading...</slot>
<p v-else>Searching...</p>
</div>
</template>
Edit 2: As pointed out by #GoogleMac in the comments, checking for a slot's text property fails for renderless components (e.g. <transition>, <keep-alive>, ...), so the check they suggested is:
!!this.$slots.default && !!this.$slots.default[0]
// or..
!!(this.$slots.default || [])[0]
#kano's answer works well, but there's a gotcha: this.$slots isn't reactive, so if it starts out being false, and then becomes true, any computed property won't update.
The solution is to not rely on a computed value but instead on created and beforeUpdated (as #MathewSonke points out):
export default {
name: "YourComponentWithDynamicSlot",
data() {
return {
showFooter: false,
showHeader: false,
};
},
created() {
this.setShowSlots();
},
beforeUpdate() {
this.setShowSlots();
},
methods: {
setShowSlots() {
this.showFooter = this.$slots.footer?.[0];
this.showHeader = this.$slots.header?.[0];
},
},
};
UPDATE: Vue 3 (Composition API)
For Vue 3, it seems that the way to check whether a slot has content has changed (using the new composition API):
import { computed, defineComponent } from "vue";
export default defineComponent({
setup(_, { slots }) {
const showHeader = computed(() => !!slots.header);
return {
showHeader,
};
},
});
note: I can't find any documentation on this, so take it with a pinch of salt, but seems to work in my very limited testing.
this.$slots can be checked to see if a slot has been used.
It is important to note that this.$slots is not reactive. This could cause problems when using this.$slots in a computed value.
https://v2.vuejs.org/v2/api/?redirect=true#:~:text=Please%20note%20that%20slots%20are%20not%20reactive.
This means we need to ensure that this.slots is checked whenever the component re-renders. We can do this simply by using a method instead of a computed property.
https://v2.vuejs.org/v2/guide/computed.html?redirect=true#:~:text=In%20comparison%2C%20a%20method%20invocation%20will%20always%20run%20the%20function%20whenever%20a%20re%2Drender%20happens
<template>
<div>
<slot v-if="hasHeading" name="heading"/>
</div>
</template>
<script>
export default{
name: "some component",
methods: {
hasHeading(){ return !!this.slots.heading}
}
}
</script>