Displaying a selected object as string in vuejs - vue.js

Below is my html code that am using to implement select2
<!DOCTYPE html>
<html>
<head>
<title>department</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.12/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" ></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.12/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="ProgramForm">
<div class="form-row">
<div class="form-group col-md-4">
<label for="department">Department<span style="color:red">*</span></label>
<select v-model="department" class="form-control select2" >
<option> </option>
<option v-for="department in departmentData" v-bind:value="department">{{department.departmentName}}</option>
</select>
</div>
</div>
<p>Selected{{department}}</p>
</div>
My script section is as follows
<script type="text/javascript" >
$(function () {
var programFormVM=new Vue({
el:"#ProgramForm",
data:function(){
return {
department:{},
departmentData:[
{ "id": 1, "departmentCode": "HR", "departmentName": "Human Resource" },
{ "id": 2, "departmentCode": "ENG", "departmentName": "Engineering" },
{ "id": 3, "departmentCode": "AE", "departmentName": "Agricultural Economics" },
{ "id": 4, "departmentCode": "FS", "departmentName": "Field Station" },
{ "id": 5, "departmentCode": "ARC", "departmentName": "Architecture" }
]
}
},
created:function (){
},
methods:{
},
});
$('.select2').select2({
placeholder: "Select a department"
}).on('change', function(e) {
// var data = $(".select2 option:selected").val();
programFormVM.department=$(".select2 option:selected").val();
});
});
</script>
</body>
</html>
I need to display the object as a string. As it is, an getting [object Object].I Have tried .text() but its giving the name of the department only. I my case i need the whole object but as a string like { "id": 5, "departmentCode": "ARC", "departmentName": "Architecture" }. Please help out. Regards.

v-bind:value="department.id"
const selectedValue = <value from select>
const selectedDepartment = this.departmentData.find(x => x.id === selectedVal)

Related

VueJS click events in compoments

I've made a component (is that overkill?) to call recursively in order to render a tree, but it seems to be impossible to handle click events because stuff rendered inside the component can't see the method I want in the Vue's methods; this appears to be some monstrous complication about components and events.
How can I handle these click events?
Does it really have to be so difficult?
<script type="text/html" id="template-tree">
<ul>
<c-tree-item v-for="item in items" v-bind:item="item"></c-tree-item>
</ul>
</script>
<script type="text/html" id="template-tree-item">
<li v-on:click="clickTreeItem"> <!-- click doesn't work :( -->
<p> {{ item.Name }}</p>
<ul v-if="item.Items.length > 0">
<c-tree-item v-for="i in item.Items" v-bind:item="i"></c-tree-item>
</ul>
</li>
</script>
<script type="text/javascript">
var vueApp = undefined;
var ct = Vue.component('c-tree', {
template: document.getElementById('template-tree').innerHTML,
props: ['items']
});
var cti = Vue.component('c-tree-item', {
template: document.getElementById('template-tree-item').innerHTML,
props: ['item']
});
$(document).ready(function () {
var router = new VueRouter({
mode: 'history',
routes: []
});
vueApp = new Vue({
router,
el: '#vue',
data: {
tree: JSON.parse(document.getElementById('data').innerHTML)
},
methods: {
clickTreeItem: function(event) {
console.log('click');
console.log(JSON.stringify(event));
}
}
});
});
</script>
<div id="vue">
<c-tree v-bind:items="tree"></c-tree>
</div>
A component can only raise events -- which may have data associated with them.
A component has to listen to it's sub-components' events and may, in turn, pass them upwards as its own events.
Example: https://jsfiddle.net/gkch7bnr/1/
StackOverflow is stroppy about JSFiddle so here is some code:
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.common.dev.js" integrity="sha256-soI/D3XnqcarOMK229d8GWs8P+gYViEsbWBeMaRoSPk=" crossorigin="anonymous"></script>
<script type="application/json" id="data">
[
{"Id": 1, "Name": "Name1", "Items": []},
{"Id": 2, "Name": "Name2", "Items": []},
{"Id": 3, "Name": "Name3", "Items": [
{"Id": 31, "Name": "Name31"},
{"Id": 32, "Name": "Name32"},
{"Id": 33, "Name": "Name33"}
]}
]
</script>
<script type="text/html" id="template-tree">
<ul>
<c-tree-item v-for="item in items" v-bind:item="item" v-on:click="$emit('click', $event)"></c-tree-item>
</ul>
</script>
<script type="text/html" id="template-tree-item">
<li>
<p v-on:click="$emit('click', item)" > {{ item.Name }}</p>
<ul v-if="item.Items && item.Items.length > 0">
<c-tree-item v-for="i in item.Items" v-bind:item="i" v-on:click="$emit('click', $event)"></c-tree-item>
</ul>
</li>
</script>
</head>
<body>
<div id="vue">
<c-tree v-bind:items="tree" v-on:click="clickTreeItem"></c-tree>
</div>
</body>
var vueApp = undefined;
var ct = Vue.component('c-tree', {
template: document.getElementById('template-tree').innerHTML,
props: ['items'],
methods: {
clickTI: function(e) { console.log('clickTI: ' + e.Name);}
}
});
var cti = Vue.component('c-tree-item', {
template: document.getElementById('template-tree-item').innerHTML,
props: ['item']
});
$(document).ready(function () {
vueApp = new Vue({
el: '#vue',
data: {
tree: JSON.parse(document.getElementById('data').innerHTML)
},
methods: {
clickTreeItem: function(event) {
console.log('clickTreeItem: ' + event.Name);
}
}
});
});

How to use href in Vue and Quill

I am using the Quill editor in Vue.js and it's working great. I have images, etc.
But...the link isn't working. I tried both the "snow" and "bubble" themes.
I type the text, highlight it and then click on the "link". I get the dialog to set the link, but then the link isn't there.
It's working in the JavaScript version, but not the Vue.
Below is my code.
Vue.component('editor', {
template: '<div ref="editor"></div>',
props: {
value: {
type: String,
default: ''
}
},
data: function() {
return {
editor: null
};
},
mounted: function() {
this.editor = new Quill(this.$refs.editor, {
modules: {
toolbar: [
[{ header: [1, 2, 3, 4, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block', 'link']
]
},
//theme: 'bubble',
theme: 'snow',
formats: ['bold', 'underline', 'header', 'italic', 'link'],
placeholder: "Type something in here!"
});
this.editor.root.innerHTML = this.value;
this.editor.on('text-change', () => this.update());
},
methods: {
update: function() {
this.$emit('input', this.editor.getText() ? this.editor.root.innerHTML : '');
}
}
})
new Vue({
el: '#root',
data: {
//model: 'Testing an editor'
model: '',
isShowing: true
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<link href="https://cdn.quilljs.com/1.3.4/quill.snow.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://cdn.quilljs.com/1.3.4/quill.core.css" rel="stylesheet"/>
<!DOCTYPE html>
<html>
<head>
<title>Trying to use the Quill Editor in Vue</title>
</head>
<body>
<div id="root">
<div v-if="isShowing">
<editor v-model="model"></editor>
</div>
<p>I need the v-html directive: <span v-html="model"></span></p>
<p>Raw data: <pre>{{ model }}</pre></p>
<button #click="isShowing = !isShowing">Toggle</button>
</div>
</script>
</body>
</html>
Any help is greatly appreciated.
Thanks, D
I had to place a 'link' into the "formats" as well:
formats: ['bold', 'underline', 'header', 'italic', 'link'],
I updated my code snippet with the correct answer in case anyone else is having this problem.
Thanks!

Not able to access data variable in script but can in html

I have populated a data variable with an array, and can access its contents by using a v-for in the html, but I can't access any of the data in the variable within the script, and I don't know why.
var result = [{
"CatalogName": "Retro Doors",
"ItemName": "French Doors",
"ItemListPrice": "$461.00",
"ItemType": "Oak",
"ItemFeatures": [{
"Features": "Door Quantity",
"QTY": 2
},
{
"Features": "Door Hinges",
"QTY": 4
},
{
"Features": "Door Knobs",
"QTY": 1
},
{
"Features": "Door Looks",
"QTY": 1
},
{
"Features": "Glass Panes",
"QTY": 2
}
]
}];
new Vue({
el: '#app',
beforeCreate: function() {
console.log("Before Created");
},
created: function() {
console.log("Created");
this.GetItemsList();
},
beforeMount: function() {
console.log("Before Mount");
},
data: {
itemPriceList: []
},
methods: {
GetItemsList() {
this.itemPriceList = result;
}
},
mounted: function() {
console.log("Mounted");
console.log(this.ItemPriceList);
}
});
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
<div id="app">
{{ itemPriceList[0].CatalogName }}
<div v-for="item in itemPriceList">
{{ item.ItemName }}
<div v-for="items in item.ItemFeatures">
{{ items.Features }} : {{ items.QTY }}
</div>
</div>
</div>
You have a typo in a variable name inside mounted hook - used with capital I.
In data: itemPriceList
In mounted hook: this.ItemPriceList
Should be the same as defined inside data property.

Vue.js render a component with scope slot but return NaN

I am a fresher.I try to use scope slot and directive to create a list sample ,the code follow:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>作用域插槽</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="app">
<app></app>
</div>
</body>
<script>
Vue.directive("selectall",{
bind:function(el,binding,vnode,oldVnode){
var arg = binding.arg,
value = binding.value;
console.log(arg,value);
$(el).on('change',function(){
});
}
});
Vue.component("list",{
template:"<div><ul>"
+"<slot name='item' v-for='item in litodos' :text= 'item.text' :time='item.time' :idx='item.idx'></slot>"
+"</ul>"
+"</div>",
props:['litodos'],
data:function(){
return {
message:"list-message"
}
}
});
Vue.component("app",{
template:"<div class='container'>"
+" <input type='checkbox' v-selectall:parent='group1'/>select all gruop1"
+"<list :litodos='todos1'>"
+"<template slot='item' scope='props'>"+
+"<li><input type='checkbox' value='{{props.idx}}' v-selectall:child='group1'/>{{props.text}} </li>"
+"</template>"
+"</list>"
+" <hr><input type='checkbox' v-selectall:parent='group2'/>select all gruop2"
+"<list :litodos='todos2'>"
+"<template slot='item' scope='props'>"+
+"<li><input type='checkbox' value='{{props.idx}}' v-selectall:child='group2'/>{{props.text}}</li>"
+"</template>"
+"</list>"
+"</div>",
data:function(){
return {
group1:"group1",
group2:"group2",
todos1:[
{
text:'study english',
time:'3hour',
idx:'1'
},{
text:'study vue',
time:'2hour',
idx:'2'
}
],
todos2:[
{
text:'学英语',
time:'3hour',
idx:'3'
},{
text:'学js',
time:'2hour',
idx:'4'
}
]
};
}
})
var app = new Vue({
el: '#app',
data:{}
});
</script>
</html>
and here are essential fragment:
+"<list :litodos='todos1'>"
+"<template slot='item' scope='props'>"+
+"<li><input type='checkbox' value='{{props.idx}}' v-selectall:child='group1'/>{{props.text}} </li>"
+"</template>"
+"</list>"
but the result is like this:
enter image description here
I find out that the slot return to NaN,so I am so confused.Can you help me find the keys point to resolve this bug?Thank you!

How to place checkboxes in a tree?

Can someone suggest how can I place check boxes against each folder of the below tree hierarchy? I am trying to add check-boxes but it is not showing up in my tree shown below. Please suggest the changes i need to make for my below code to get the checkbox displayed. This is a working code , just copy paste the same in a textpad and open in IE allowing activex.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/resources/dojo.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojox/grid/resources/Grid.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojox/grid/resources/claroGrid.css">
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js"
data-dojo-config="isDebug: true,parseOnLoad: true"></script>
<link rel="stylesheet" href="css/style.css" media="screen">
<script>
dojo.require("dojo.parser");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.Select");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.tree.ForestStoreModel");
dojo.require("dijit.tree.dndSource");
dojo.require("dijit.Tree");
dojo.addOnLoad(function() {
dojo.byId('loaderInner').innerHTML += " done.";
setTimeout(function hideLoader(){
dojo.fadeOut({
node: 'loader',
duration:500,
onEnd: function(n){
n.style.display = "none";
}
}).play();
}, 250);
});
var store;
var selectedItemId = 0;
var itemSelected = null;
var sel = null;
var idCount = 0;
var treeModel;
var mytree;
var modeSelector;
dojo.ready(function(){
store = new dojo.data.ItemFileWriteStore({
contentType: 'application/json',
target: 'store',
url: "http://pmis.biz/rwa/data/ProjectList.php"
});
treeModel = new dijit.tree.ForestStoreModel({
iconClass: 'dijitEditorIcon dijitEditorIconCut',
store: store,
query: {"main": 0},
rootId: 0,
rootLabel: "project",
pasteItem: function(){},
mayHaveChildren : function(item) {
return true;
},
getChildren: function(parentItem, callback, onError) {
if(parentItem.root == true ){
if(this.root.children){
callback(this.root.children);
}else{
this.store.fetch({
query: this.query,
queryOptions: {cache:false},
onComplete: dojo.hitch(this, function(items){
this.root.children = items;
callback(items);
}),
onError: onError
});
}
} else {
console.debug("Tree child onLoad here: "+parentItem.id);
if (idCount < parseInt(parentItem.id)){
idCount = parseInt(parentItem.id);
}
var sx = parseInt(parentItem.id);
this.store.fetch({
query: { main: sx },
queryOptions: {cache:false},
onComplete: dojo.hitch(this, function(items){
this.root.children = items;
callback(items);
}),
onError: onError
});
}
}
});
mytree = new dijit.Tree({
model: treeModel,
openOnClick:true,
showRoot: true,
setCheckboxOnClick : true,
// onDblClick: function (item, node, evt){
// },
onClick: function (item, node, evt){
resetEditor();
}
}, "treeThree");
});
</script>
</head>
<body class="claro">
<!-- BorderContainer -->
<div id="main" data-dojo-type="dijit.layout.BorderContainer"
data-dojo-props="liveSplitters:false, design:'headline',
style:'width:100%; height:100%; max-width:1050px; min-width:680px; min-height:400px; margin: 0 auto;'">
<!-- AccordionContainer-->
<div data-dojo-type="dijit.layout.AccordionContainer"
data-dojo-props="region:'leading', splitter:true, minSize:20" style="width: 630px;" id="leftAccordion">
<div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:'NG Tree Hierarchy'">
<div data-dojo-type="dijit.layout.ContentPane"
data-dojo-props="title:'Rootless Tree',
style:'width:30%; height:100%; max-width:1050px; min-width:250px; min-height:300px; margin: 0 auto; float:left'">
<div id="treeThree"></div>
</div>
<div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:'Rootless CCCCCC'">
<!-- Project selector -->
<div id=help"></div><br>
<br>
<!-- <select id="f_2"></select>-->
<br>
<div>
<table style="width: 135px; height: 83px;">
<tr><td>
<div id="ip"></div>
</tr><tr><td>
<button id="bd" data-dojo-type="dijit.form.Button" style="visibility:hidden"
data-dojo-id="bd"
data-dojo-props="disabled: true,
onClick: function (evt){
store.deleteById(selectedItemId);
resetEditor();
},
label:'Delete project' ">
</button>
<button id="bs" data-dojo-type="dijit.form.Button" style="visibility:hidden"
data-dojo-id="bs"
data-dojo-props="disabled: true,
onClick: function (evt){
var lvalue = dijit.byId('s1').value;
store.setValue(itemSelected, 'title', dijit.byId('s1').value);
store.setValue(itemSelected, 'description', dijit.byId('s2').value);
store.save();
},
label:'Save project' ">
</button>
<button id="ba"data-dojo-type="dijit.form.Button" style="visibility:hidden"
data-dojo-id="ba"
data-dojo-props="disabled: true,
onClick: function (evt){
idCount = idCount +1;
var newItem = {};
newItem.id = idCount;
newItem.main = selectedItemId;
newItem.title = dijit.byId('s1').value;
newItem.description = dijit.byId('s2').value;
store.newItem(newItem);
sel.setStore(store,'',{query:{main: 0}});
/* mytree.update();*/
},
label:'Add project' ">
</button>
<br>
<button onclick="mytree.refreshModel()" style="visibility:hidden">
Update
</button>
</tr>
</table>
<br>
</div>
</div>
</div>
<div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:''">
<div></div>
</div>
</div>
<div id="header" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'top'">
</div>
<!-- Top tabs (marked as "center" to take up the main part of the BorderContainer) -->
<div data-dojo-type="dijit.layout.TabContainer" data-dojo-props="region:'center', tabStrip:true" id="topTabs">
<div id="basicFormTab1" data-dojo-type="dijit.layout.ContentPane"
data-dojo-props="title:'Tab1', style:'padding:10px;display:none;'">
<p> </p>
</div>
<div id="basicFormTab2" data-dojo-type="dijit.layout.ContentPane"
data-dojo-props="title:'Tab2', style:'padding:10px;display:none;'">
<p> </p>
</div>
<div id="basicFormTab3" data-dojo-type="dijit.layout.ContentPane"
data-dojo-props="title:'Tab3', style:'padding:10px;display:none;'">
<p> </p>
</div>
</div>
</div>
</body>
</html>
A library was created for this:
http://www.thejekels.com/dojo/cbtree_AMD.html
The instruction manual is kind of hard to find from that site. It is a github wiki here: https://github.com/pjekel/cbtree/wiki/CheckBox-Tree. Download the git repo, then follow instructions at https://github.com/pjekel/cbtree/wiki/Installation, and you should be good to go.
Try this one (tested on dojo 1.10):
require(["dojo/_base/connect", "dijit/dijit", "dojo/data/ItemFileReadStore", "dijit/Tree", "dijit/form/CheckBox",
"dojo/domReady!"],
function (connect, dijit, ItemFileReadStore, Tree, CheckBox) {
var store = new ItemFileReadStore({
data: {
identifier: 'id',
label: 'label',
items: rawdata
}
});
var treeControl = new Tree({
store: store,
showRoot: false,
_createTreeNode: function (args) {
var tnode = new Tree._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
var cb = new CheckBox();
cb.placeAt(tnode.labelNode, "first");
connect.connect(cb, "onChange", function () {
var treeNode = dijit.getEnclosingWidget(this.domNode.parentNode);
connect.publish("/checkbox/clicked", [{
"checkbox": this,
"item": treeNode.item
}]);
});
return tnode;
}
}, "CheckboxTree");
connect.subscribe("/checkbox/clicked", function (message) {
console.log("you clicked:", store.getLabel(message.item));
});
}); // require
var rawdata = [{
label: 'Level 1',
id: '1',
children: [{
label: 'Level 1.1',
id: '1.1',
active: true
},
{
label: 'Level 1.2',
id: '1.2',
active: true
}]
},
{
label: 'Level 2',
id: '2',
children: [{
id: '2.1',
label: 'Level 2.1',
active: false
},
{
id: '2.2',
label: 'Level 2.2',
active: true
},
{
id: '2.3',
label: 'Level 2.3',
active: true
}]
}];