Vuejs
i have a trouble with a vue script for tree view component
I modified a script for tree view of vue, it works but i have a problem when i do click over the parent li, beacuse it is opened all li elements of the same level and i need to open only the li who i clicked.
on the original script is added a children elements when you clicked two times, but in the modified script is not required.
i dont know who is the problem with the script, i tryed to open the element of the list by index but it is not working
Original script:
// demo data var data = { name: 'My Tree', children: [ { name: 'hello' }, { name: 'wat' }, { name: 'child folder', children: [ { name: 'child folder', children: [ { name: 'hello' }, { name: 'wat' } ] }, { name: 'hello' }, { name: 'wat' }, { name: 'child folder', children: [ { name: 'hello' }, { name: 'wat' } ] } ] } ] } // define the item component Vue.component('item', { template: '#item-template', props: { model: Object }, data: function () { return { open: false } }, computed: { isFolder: function () { return this.model.children && this.model.children.length } }, methods: { toggle: function () { if (this.isFolder) { this.open = !this.open } }, changeType: function () { if (!this.isFolder) { Vue.set(this.model, 'children', []) this.addChild() this.open = true } }, addChild: function () { this.model.children.push({ name: 'new stuff' }) } } }) // boot up the demo var demo = new Vue({ el: '#demo', data: { treeData: data } }) body { font-family: Menlo, Consolas, monospace; color: #444; } .item { cursor: pointer; } .bold { font-weight: bold; } ul { padding-left: 1em; line-height: 1.5em; list-style-type: dot; } <script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script> <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div :class="{bold: isFolder}" @click="toggle" @dblclick="changeType"> {{model.name}} <span v-if="isFolder">[{{open ? '-' : '+'}}]</span> </div> <ul v-show="open" v-if="isFolder"> <item class="item" v-for="model in model.children" :model="model"> </item> <li class="add" @click="addChild">+</li> </ul> </li> </script> <p>(You can double click on an item to turn it into a folder.)</p> <!-- the demo root element --> <ul id="demo"> <item class="item" :model="treeData"> </item> </ul>
Modified Tree View:
// demo data var data = [ { "id":"{module:1}", "title":"Almacenes", "children":[ { "id":1, "title":"demox", "children":[ { "id":2, "title":"aaaa" } ] }, { "id":2, "title":"Compras" }, { "id":3, "title":"Bancos" }, { "id":4, "title":"Contabilidad" }, { "id":5, "title":"Gestion de Ventas" } ] }, { "id":"{module:2}", "title":"Inicio", "children":[ { "id":7, "title":"Punto de Venta" } ] } ] // define the item component Vue.component('item', { template: '#item-template', props: { model: {} }, data: function () { return { open: false } }, methods: { isFolder: function (key) { return this.model[key].children && this.model[key].children.length }, toggle: function (key) { console.log(key); if (this.isFolder(key)) { console.log(this); this.open = !this.open; //this.$children[key].open = !this.$children[key].open; //console.log(this.$children[key].open); } }, changeType: function (key) { if (!this.isFolder(key)) { Vue.set(this.model[key], 'children', []) this.addChild() this.open = true } }, addChild: function (key) { this.model[key].children.push({ name: 'new stuff' }) } } }) // boot up the demo var demo = new Vue({ el: '#demo', data: { treeData: data } }) body { font-family: Menlo, Consolas, monospace; color: #444; } ul{ list-style-type: none; } .item { cursor: pointer; } .bold { font-weight: bold; } ul { padding-left: 1em; line-height: 1.5em; list-style-type: dot; } <script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script> <!-- item template --> <script type="text/x-template" id="item-template"> <ul> <li v-for="(item, index) in model" :key="index"> <div :class="{bold: isFolder(index)}" @click="toggle(index)" >{{ item.title }} <span v-if="isFolder(index)">[{{open ? '-' : '+'}}]</span> </div> <ul v-show="open" v-if="isFolder(index)"> <item class="item" :model="item.children"> </item> <li class="add" @click="addChild(index)">+</li> </ul> </li> </ul> </script> <p>(You can double click on an item to turn it into a folder.)</p> <!-- the demo root element --> <div id="demo"> <item class="item" :model="treeData"> </item> </div>
I'm getting a "[Vue warn]: Error compiling template:" error in my Vue Application when trying to use a custom compnent
full error;
[Vue warn]: Error compiling template: Navbar - Component template requires a root element, rather than just text. found in ---> <Navbar> <Home> at C:\Users\admin\Documents\Coding\Websites\Total- Response\src\components\Home.vue <App> at C:\Users\admin\Documents\Coding\Websites\Total- Response\src\App.vue <Root>It's not rendering any content on screen though the vue in browser tool detects the Navbar custom component. I think it might be something with how I'm declaring my component but i'm still fairly new at vue. I've looked all over for solutions but to no avail, so any help would be greatly appreciated!
code;
-main.js
-app.vue
<template> <div id="app"> <header> </header> <main> <router-view></router-view> </main> </div> </template> <script> export default { name: 'app' } </script> <style lang="less"></style>-home.vue
<template> <div> <navbar></navbar> </div> </template> <script> export default { name: 'home' } </script> <style lang="less"> </style>-navbar.vue
<template name="Navbar"> <div id="Navbar" class="nav"> <a href="index.html"><div class="logo"></div></a> <div class="navButton"> <center><div class="navButtonIcon"></div></center> </div> <div class="navpane"> <center> <a href="portfolio.html"><div class="navtile">Portfolio</div></a> <a href="packages.html"><div class="navtile">Packages</div></a> <a href="contact.html"><div class="navtile">Contact Us</div></a> <a href="login.html"><div class="navtile">Login</div></a> </center> </div> </div> </template> <script> export default { name: 'Navbar' } </script> <style lang="less"> @backgroundColor: #355477; @secondaryColor: #23374c; @textColor: #000; @baseFontSize: 1em; .nav { position: fixed; top: 0; left: 0; width: 100vw; height: 150px; background-color: @backgroundColor; display: grid; grid-template-columns: 20px repeat(7, 1fr) 10px; z-index: 2; } .logo { background-image: url("../assets/TotalResponseLogo.png"); background-repeat: no-repeat; margin-left: 20px; grid-column-start: 2; grid-column-end: 4; height: 150px; width: 250px; } .navButton { grid-column-start: 8; grid-column-end: 9; width: 150px; height: 150px; -webkit-tap-highlight-color: rgba(0,0,0,0); } .navButtonIcon { width: 80px; height: 80px; padding: 10px 0; background: url("../assets/navbuttonAnimation.svg"); background-position: 0px; background-repeat: no-repeat; } .navpane { position: absolute; top: -2000px; width: 100%; z-index: -1; } .navtile { width: 90%; height: 80px; border-radius: 5px; margin: 10px 0; padding-top: 18px; background-color: @secondaryColor; text-align: center; font-size: @baseFontSize + 1em; text-decoration: none; color: @textColor; z-index: -1; } @keyframes activateNav { from {top: -2000px;} to {top: 100px;} } @keyframes activateNavtiles { 0% {margin: 10px 0;} 40% {margin: 14px 0;} 80% {margin: 26px 0;} 100% {margin: 12px 0;} } @keyframes deactivateNav { 0% {top: 80px;} 99% {top: 2000px;} 100% {top: 2000px; display: none;} } @keyframes deactivateNavtiles { 0% {margin: 12px 0;} 50% {margin: 18px 0;} 100% {margin: 26px 0;} } @keyframes navButtonAnimation { 100% {background-position: -1440px;} } @keyframes navButtonAnimationReverse { 0% {background-position: -1440px;} 100% {background-position: 0px;} } .navpaneAnimation { animation-name: activateNav; animation-duration: .7s; animation-iteration-count: 1; animation-fill-mode: forwards; display: inline; } .navtileAnimaton { animation-name: activateNavtiles; animation-duration: 1.5s; animation-iteration-count: 1; animation-fill-mode: forwards; } .navpaneAnimationExit { animation-name: deactivateNav; animation-duration: 1.5s; animation-iteration-count: 1; animation-fill-mode: forwards; } .navtileAnimatonExit { animation-name: deactivateNavtiles; animation-duration: 1.5s; animation-iteration-count: 1; animation-fill-mode: forwards; } .navButtonAnimation { animation: navButtonAnimation .4s steps(18); animation-iteration-count: 1; animation-fill-mode: forwards; } .navButtonAnimationExit { animation: navButtonAnimationReverse .5s steps(18); animation-iteration-count: 1; animation-fill-mode: forwards; } a { text-decoration: none; } </style>Create dynamic channels using Laravel echo and broadcasting
I'm trying to create a chat in which users can create 1 on 1 conversations or even group conversations. I'm using Laravel 5.5 and Vue.js
From what I read from the documentation to join a chat, with a wild card is trough:
Echo.join('chat.'{roomId}) //.here() //.joining() //.leaving() .listen('MessagePosted', (e) => { //Some action }); });and in routes/channels.php I should use
Broadcast::channel('chat.{roomId}', function ($user, $roomId) { //some form of authentication });But where should I place the Echo function?
I'm creating the Vue app through
const app = new Vue({ el: '#app', data: { //Some arrays }, methods: { //some methods }, created() { //some axios functions to happen when it is created Echo.join('chatroom') //.here() //.joining() //.leaving() .listen('MessagePosted', (e) => { console.log(e); this.messages.push({ message: e.message.message, user: e.user }); }); }});
As you can see I used to create a general channel in which every instance created of #app would join but I want to change that to join just a certain channel.
PouchDB and Vue.js integration
Did anyone of you integrate PouchDB / vue-pouch-db within your Vue.js app? I got an error when defining PouchDB database.
I had used below definitions:
import PouchDB from 'pouchDB' or import PouchDB from 'vue-pouch-db' or const PouchDB = require('vue-pouch-db') const db = new PouchDB('database_name') or const db = PouchDB('database_name')None of them works for me.
Errors:
- when declaring new PouchDB = > PouchDB is not a constructor
- when declaring PouchDB = > PouchDB is not a function
What is the proper way to initialize PouchDB in Vue ?? Thanks a lot !
Vue.js conditional module styles
I want to separate the styles in a Vue.js component in modules. Each style module will have far more than just a class, and new classes will be added regularly. So, it will be hard to change the entire component's template. So, I'm looking for a more practical solution.
I came with the idea of, using a v-if in the styles, but not exactly sure how it should be implemented or if such thing is possible after all.
It will be way more practical, if just depending on the name sent with props, the entire styles changes.
<template> <div class="color-text"> Text in the color of the class with just the name </div> </template> <script> export default { name: 'comp', props: ['name'] } </script> <!-- General styles --> <style scoped> div{ float: right; } </style> <!-- red styles --> <style module v-if="name === 'red'"> .color-text{ color: red; } </style> <!-- blue styles --> <style module v-if="name === 'blue'"> .color-text{ color: blue; } </style> <!-- green styles --> <style module v-if="name === 'green'"> .color-text{ color: green; } </style>v-for with dynamic keys
Very new to Vuejs 2. Have a question on how to enumerate through a dynamic set of data that has a dynamic key? Take this data for instance (this is from a 3rd party -- so unable to change data -- and shortened for readability):
{ "143": { "account_id": 1, "name": "Account 1", "groups": [ { "1610": { "name": "Group 1610", "meetings": [ { "20170816": [ { "id": 10755, "name": "Untitled" } ] } ] } } ] } }Then I have a .vue file that has a template that does this:
<div v-for="(account, accountKey) in accounts"> <div>{{ account.name }} ({{ accountKey }})</div> <div v-for="(group, groupKey) in groups"> <div>{{ group.name }} ({{ groupKey }})</div> <div v-for="(meeting, meetingKey) in meetings"> <div>{{ meeting.name }} ({{ meetingKey }})</div> </div> </div> </div>This doesn't render anything. There are several things I need to here, but not sure how to accomplish in Vuejs.
- Need to be able to pull the key (as it's the identifier) for each of the records.
- Need to be able to access the individual data on record, of course.
Anyone come across something similar that can help with?
Thanks!
How to use vue resource to call sync ajax calls?
I am trying multiple ajax calls and I need syn call of ajax, how to set up in vue resource for sync ajax call.
Upload file with vue and receive it nodejs
I am trying to upload a file to the server with vuejs, actually i don't want the form to treat the file and upload it, i prevent the submit and treat some logic by myself, so at the begin i want to do something simple just check if it is a pdf and if everything is ok it should point to /upload in the localhost defined for NodeJS server
<template> <div id="app"> <form> <h2>Select a file</h2> <input id="inputVal" type="file" @change="onFileChange"> <button @click.prevent="sendFile()">Send</button> </form> </div> </template> <!-- Javascript --> <script> export default { name: 'app', data() { return { file: '' } }, methods: { onFileChange(e) { var files = e.target.files || e.dataTransfer.files; if (!files.length) { return; } var ext = files[0].name.split('.').pop(); if(ext === 'pdf') { this.createFile(files[0]); } else { this.file = ''; this.clearFileInput(document.getElementById('inputVal')); } }, createFile(file) { this.file = file; }, clearFileInput(ctrl) { try { ctrl.value = null; } catch(ex) { } if (ctrl.value) { ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl); } }, sendFile() { var vm = this; if(this.file !== '') { this.$http.post('http://localhost:3000/upload',{params: vm.file, headers: {'Content-Type': 'multipart/form-data'}}) .then(response => { // JSON responses are automatically parsed. // }, error => { //this.errors.push(e) }); } } } } </script>on my server side i am receiving undefined, i don't really know why, i just wanna see if i really got any file in the server, and if yes i want to save it on the server side, any help with that?
i just did this on the /upload endpoint:
router.post('/upload',function(req,res) { console.log(res.body); })quasar framework - colour and font size of stacked label
I am using the latest quasar framework. I want to change the colour and font size of the stacked label in a q-input field. Changing the in the css doesn’t seem to take effect. Any local styling apply only to the input text and not to the label. how to solve this problem? Thanks, Priy
Vue.ks transition on replacing list
I faced up with problem which described in vue.js official documentation here, but with kidna different data. I want to create tree-like structure with items and sub-items to describe tree (files and folders structure is good example). To make some visual enhancement I wanted to make them sliding, but got that. mode="out-in" was already set and made no effect.
Any idea how to fix this transition?
Vue.component('booster', { props: { item: { type: Object } }, template: '<div class="booster" @click="$emit(\'click\')"><img :src="item.image"></div>' }); Vue.component('boosters', { data: function() { return { boosters: this.items, path: [], root: this.items }; }, props: { items: { type: Array }, item_up: { type: Object, default: function() { return { name: "Up", image: "http://via.placeholder.com/128x178/000000/ffffff?text=↑" }; } } }, methods: { navigate: function(item) { var self = this; if (item === self.item_up && self.path.length) { self.root = self.path.pop(); } else if ("undefined" !== typeof item.items) { self.path.push(self.root); self.root = [self.item_up].concat(item.items); } else { console.log(item.name); } } }, template: '<transition-group name="slide" mode="out-in" tag="div" class="boosters"><template v-for="item in root"><booster :item="item" :key="item.name" @click="navigate(item)"></booster></template></transition-group>' }); var vue = new Vue({ el: '#content' }); #content { margin: 4rem; } .boosters { display: flex; flex-wrap: wrap; align-content: center; } .booster { box-shadow: 0px 0px 6px 3px black; box-sizing: border-box; margin: 15px; } .booster img { width: 128px; height: 178px; display: block; } .slide-enter-active, .slide-leave-active { transition: all 0.6s ease-in-out;*/ } .slide-move { transition: transform 0.5s; } .slide-enter { transform: translateY(-100%); } .slide-leave-to { transform: translateY(100%); } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.3/vue.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="content"> <boosters :items='[ {name:"First",image:"http://via.placeholder.com/128x178?text=1",items:[ {name:"Sub-first-1",image:"http://via.placeholder.com/128x178?text=1.1"}, {name:"Sub-first-2",image:"http://via.placeholder.com/128x178?text=1.2"} ]}, {name:"Second",image:"http://via.placeholder.com/128x178?text=2", items:[ {name:"Sub-second-1",image:"http://via.placeholder.com/128x178?text=2.1"}, {name:"Sub-second-2",image:"http://via.placeholder.com/128x178?text=2.2"} ]}, {name:"Third",image:"http://via.placeholder.com/128x178?text=3"} ]'> </booster> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script> </div> </body> </html>
How to pass data from Vue js method scope to external JS file?
This my component code of vue js
<template> <div class="grapha"> <div id="chart2"></div> </div> </template> <script> // var apiURL = 'https://jsonplaceholder.typicode.com/users'; var apiURL = 'http://localhost:3000/db'; export default { name: 'grapha', data () { return { users:[] } }, methods: { fetchData: function () { var self = this; $.get( apiURL, function( data ) { self.users = data; }); } }, created: function (){ this.fetchData(); } } </script>
Here is my d3 combo chart code , here is a variable named Data takes values and shows it on graph.
Now, I want to get data from self.users (vue js component) to pass it on data variable ( external function ). Could you suggest me what would be the possible way to do that ?
function getTextWidth(text, fontSize, fontName) { c = document.createElement("canvas"); ctx = c.getContext("2d"); ctx.font = fontSize + ' ' + fontName; return ctx.measureText(text).width; } function DataSegregator(array, on) { var SegData; OrdinalPositionHolder = { valueOf: function () { thisObject = this; keys = Object.keys(thisObject); keys.splice(keys.indexOf("valueOf"), 1); keys.splice(keys.indexOf("keys"), 1); return keys.length == 0 ? -1 : d3.max(keys, function (d) { return thisObject[d] }) } , keys: function () { keys = Object.keys(thisObject); keys.splice(keys.indexOf("valueOf"), 1); keys.splice(keys.indexOf("keys"), 1); return keys; } } array[0].map(function (d) { return d[on] }).forEach(function (b) { value = OrdinalPositionHolder.valueOf(); OrdinalPositionHolder[b] = OrdinalPositionHolder > -1 ? ++value : 0; }) SegData = OrdinalPositionHolder.keys().map(function () { return []; }); array.forEach(function (d) { d.forEach(function (b) { SegData[OrdinalPositionHolder[b[on]]].push(b); }) }); return SegData; } Data = self.users.comboChart; var margin = { top: 20, right: 30, bottom: 60, left: 40 }, width = 800 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var textWidthHolder = 0; /// Adding Date in LineCategory Data.forEach(function (d) { d.LineCategory.forEach(function (b) { b.Date = d.Date; }) }); var Categories = new Array(); // Extension method declaration // Categories.pro; var Data; var ageNames; var x0 = d3.scale.ordinal() .rangeRoundBands([0, width], .1); var XLine = d3.scale.ordinal() .rangeRoundPoints([0, width], .1); var x1 = d3.scale.ordinal(); var y = d3.scale.linear() .range([height, 0]); var YLine = d3.scale.linear().range([height, 0]) .domain([0, d3.max(Data, function (d) { return d3.max(d.LineCategory, function (b) { return b.Value }) })]); var color = d3.scale.ordinal() .range(["#6aae6a", "#639ce4", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); var line = d3.svg.line().x(function (d) { return x0(d.Date) + x0.rangeBand() / 2; }).y(function (d) { return YLine(d.Value) }); var xAxis = d3.svg.axis() .scale(x0) .orient("bottom"); // var yAxis = d3.svg.axis() // .scale(y) // .orient("left") // .tickFormat(d3.format(".2s")); // var YLeftAxis = d3.svg.axis().scale(YLine).orient("right").tickFormat(d3.format(".2s")); var svg = d3.select("#chart2").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Bar Data categories Data.forEach(function (d) { d.Categories.forEach(function (b) { if (Categories.findIndex(function (c) { return c.Name===b.Name}) == -1) { b.Type = "bar"; // console.log(JSON.stringify(b)) Categories.push(b) } }) }); // Line Data categories Data.forEach(function (d) { d.LineCategory.forEach(function (b) { if (Categories.findIndex(function (c) { return c.Name === b.Name }) == -1) { b.Type = "line"; // console.log(JSON.stringify(b)) Categories.push(b) } }) }); // Processing Line data lineData = DataSegregator(Data.map(function (d) { return d.LineCategory }), "Name"); // Line Coloring LineColor = d3.scale.ordinal(); LineColor.domain(Categories.filter(function (d) { return d.Type == "line" }).map(function (d) { return d.Name })); LineColor.range(["#333471", "#386a07", "#7f8ed4", "#671919", "#0b172b"]) x0.domain(Data.map(function (d) { return d.Date; })); XLine.domain(Data.map(function (d) { return d.Date; })); x1.domain(Categories.filter(function (d) { return d.Type == "bar" }).map(function (d) { return d.Name})).rangeRoundBands([0, x0.rangeBand()]); y.domain([0, d3.max(Data, function (d) { return d3.max(d.Categories, function (d) { return d.Value; }); })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); var state = svg.selectAll(".state") .data(Data) .enter().append("g") .attr("class", "state") .attr("transform", function (d) { return "translate(" + x0(d.Date) + ",0)"; }); state.selectAll("rect") .data(function (d) { return d.Categories; }) .enter().append("rect") .attr("width", x1.rangeBand()) .attr("x", function (d) { return x1(d.Name); }) .attr("y", function (d) { return y(d.Value); }) //.attr("height", function (d) { return height - y(d.Value); }) .style("fill", function (d) { return color(d.Name); }) .transition().delay(500).attrTween("height", function (d) { var i = d3.interpolate(0, height - y(d.Value)); return function (t) { return i(t); } }); // drawaing lines svg.selectAll(".lines").data(lineData).enter().append("g").attr("class", "line") .each(function (d) { Name=d[0].Name d3.select(this).append("path").attr("d", function (b) { return line(b) }).style({ "stroke-width": "3px", "fill": "none" }).style("stroke", LineColor(Name)).transition().duration(1500); }) // Legends var LegendHolder = svg.append("g").attr("class", "legendHolder"); var legend = LegendHolder.selectAll(".legend") .data(Categories.map(function (d) { return {"Name":d.Name,"Type":d.Type}})) .enter().append("g") .attr("class", "legend") .attr("transform", function (d, i) { return "translate(0," +( height+ margin.bottom/2 )+ ")"; }) .each(function (d,i) { // Legend Symbols d3.select(this).append("rect") .attr("width", function () { return 18 }) .attr("x", function (b) { left = (i+1) * 15 + i * 18 + i * 5 + textWidthHolder; return left; }) .attr("y", function (b) { return b.Type == 'bar'?0:7}) .attr("height", function (b) { return b.Type== 'bar'? 18:5 }) .style("fill", function (b) { return b.Type == 'bar' ? color(d.Name) : LineColor(d.Name) }); // Legend Text d3.select(this).append("text") .attr("x", function (b) { left = (i+1) * 15 + (i+1) * 18 + (i + 1) * 5 + textWidthHolder; return left; }) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "start") .text(d.Name); textWidthHolder += getTextWidth(d.Name, "10px", "calibri"); }); // Legend Placing (center) d3.select(".legendHolder").attr("transform", function (d) { thisWidth = d3.select(this).node().getBBox().width; return "translate(" + ((width) / 2 - thisWidth / 2) + ",0)"; }) // round the rectangle corners svg.selectAll('rect').attr('rx', 5).attr('ry', 5);
How to make observable with Null value in Rxjs
How are you I am newbie of Rxjs. I implemented Rxjs with Vue.js
export default { name: 'useraside', computed: { ...mapState({ userdata: state => state.app.selectedUser }) }, subscriptions () { return { // this is the example in RxJS's readme. raps: this.$watchAsObservable(this.userdata) .pluck('newValue') .distinctUntilChanged() .switchMap(data => () => { if (data) { fetchRaps(data._id) } }) .map(formatResult) } } }Here, User data is from store of vuex. And it is null at first time. So I got error such as
Error in created hook: "TypeError: Cannot read property 'toString' of null"so How can I mange this?
Vue - Reactive media .readyState
Using Vue.js, I would like to use the readyState property of an audio dom element as a reactive property.
I have the audio element in a component and accessing it with this.$refs.audioPlayer
I have tried setting a computed property to return the property:
audioLoaded(){ if(this.$refs.audioPlayer){ return this.$refs.audioPlayer.readyState; } return false; }This just returns the initial state (0), when the media is loaded, this should change to 4.
Is there any way to make this a reactive property?
Can a vue component know if a listener is listening?
Say I have a modal dialogue as a Vue component. Sometimes I want OK and Cancel. Sometimes, I just want OK. The cleanest way I can think to do this would be for my component to only display Cancel when it's caller is listening for cancel events. Can this be done?
markup
<div id="vue-root"> <confirm-modal v-on:ok="handleOk"></confirm-modal> <confirm-modal v-on:ok="handleOk" v-on:cancel="handleCancel"></confirm-modal> </div>code
Vue.component('confirm-modal',{ template : ` <div class="confirm-modal"> Are you sure<br> <button v-on:click="$emit('ok',{})">OK</button> <button v-if="'HOW DO I TEST IF CANCEL WILL BE CAPTURED???'" v-on:click="$emit('cancel',{})">Cancel</button </div> `, }) vm = new Vue({ el : '#vue-root', methods : { handleOk : function(){ alert('OK already'); }, handleCancel : function(){ } } })VueJs Tree recursive elements emits to parent
How do you emit event inside recursive child components vuejs
Taking the tree example from vue site https://vuejs.org/v2/examples/tree-view.html
How would you transmit on click to the parent each clicked elements id?
can't import vue component from npm package
Good day,
I have recently created an npm package for a navigation-bar which I want to import into my main codebase. I am using vue @components and I can't quite find out how to use the imported component. If anyone knows how to get the npm packaged component into the dom, your help would be greatly appreciated.
Below is a simplified example of what I have tried:
npm package import Vue from 'vue'; import Component from 'vue-class-component'; import '../navigation-bar.styles.less'; @Component({template: require('../navigation-bar.html')}}) export class NavigationBar extends Vue { constructor() { super(); } } Vue.component('navigation-bar', NavigationBar); main.ts import { NavigationBar } from '@international-client/navigation-bar'; Vue.component('navigation-bar', NavigationBar); index.html <html> <head> <title>Game</title> </head> <navigation-bar></navigation-bar> <body class="game-view"> </body> </html>Vuejs v-for multidimensional array json_object
I try to loop through a multidimensional json_object using the vueJS v-for function.
But i get the following error:
[Vue warn]: Error in render function: "TypeError: Cannot read property 'id' of null"
My code looks like this:
<tr v-for="timeblock in responseAPI"> <td> {{timeblock.time}} </td> <td v-for="value in timeblock.appointment"> {{value.id}} </td> <td> {{timeblock.break}} </td> <td> {{timeblock.scheduled}} </td> <td> {{timeblock.text}} </td> </tr>And my json_object like this:
[ { "time": "09:00", "break": null, "scheduled": "Stoel 1", "appointment": { "id": 1, "patient_id": 1, "chair_id": 1, "date": "2017-05-10", "time": "09:00:00", "duration": 30, "treatment_type": "Controle", "created_at": null, "updated_at": null }, "text": null }, { "time": "09:30", "break": null, "scheduled": "Stoel 1", "appointment": { "id": 2, "patient_id": 2, "chair_id": 1, "date": "2017-05-10", "time": "09:30:00", "duration": 30, "treatment_type": "Controle ", "created_at": null, "updated_at": null }, "text": null } ]Vue.js can't access this (or method return) from component method
I have a component which passes data to a method, but I need to further change the data, so I am trying (without sucess) to pass it off to a function, but it is not working, whether I place the function inside the method or outside. The problem seems to be that this is unreachable in either case, resulting in undefined warnings.
What is strange is that my second method (photoConvert) IS being called (as my console.log output proves), but the data never gets returned to the calling method (onChange). I have tried setting a value in data, tried simply returning the value, nothing works, it always shows as undefined
Here are my methods:
methods: { photoConvert (file) { var f = file var fr = new FileReader() fr.readAsDataURL(f) fr.onload = function () { var tempImage = new Image() tempImage.src = fr.result var height = tempImage.height var width = tempImage.width if (height > 150) { width = width / (height / 150) height = 150 } if (width > 150) { height = height / (width / 150) width = 150 } var c = document.createElement('canvas') c.width = width c.height = height var ctx = c.getContext('2d') ctx.drawImage(tempImage, 0, 0, width, height) var b64str = c.toDataURL('image/jpeg') console.log(b64str) //this outputs correctly, so we know it was called this.b64str = b64str //tried setting data element to no effect return b64str //never gets to method calling this function } }, onChange () { if (this.$refs.pictureInput.file) { console.log('Picture loaded.') // we got it var final64 = this.photoConvert(this.$refs.pictureInput.file) console.log(final64) // fails, says undefined } else { console.log('FileReader API not supported') } } },Vue.js - How to get last child ref in v-for children components
I want to play latest audio after page is loaded:
<player ref="player" v-for="item in data"><player>
how can I do something like this:
vm.$refs.player.last().play();
Vuejs append data-attribute conditionally
I try to add conditionally a data attribute value to my vue list on loop and I try the following
<ul data-parent="{{model.parent_id !== null ? model.parent_id : 0}}"></ul>but in this case the list do not renders anymore, if dump out outside html tag {{model.parent_id !== null ? model.parent_id : 0}} than I see the correct output