Content from async XML source doesn't get updated correctly in vue component - vue.js

Im struggeling with reactivity in vue and need some help.
My component should show content from a XML document. When switching between different XML documents, some components keep their old value and don't reflect the new content. This seems to happen for XML elements, that have the same id. However I use a unique :key attribute in the v-for loop consisting of the XML documents id and the XML elements id.
This only happens, if I set the content using a data property.
<span v-html="value"></span>
...
data() {
return {
value: this.xmlNode.firstChild.nodeValue
};
}
When I set the content directly it works as expected.
<span v-html="xmlNode.firstChild.nodeValue"></span>
HTML
<div id="course">
<button #click="toggle">Change content</button>
<edit-element
v-for="node in courseElementContent"
:xml-node="node"
:key="id + '#' + node.getAttribute('idref')"></edit-element>
</div>
JavaScript:
Vue.component('edit-element', {
template: '<div><span v-html="value"></span></div>',
props: ["xmlNode"],
data() {
return {
value: this.xmlNode.firstChild.nodeValue
};
}
});
new Vue({
el: "#course",
name: "CourseElement",
data: {
id: 1,
courseElementContent: null
},
created() {
this.load();
},
methods: {
toggle() {
if (this.id == 1) this.id = 2;
else this.id = 1;
this.load();
},
load() {
var me = this;
axios.get("content/" + this.id + ".xml").then(
response => {
var doc = new DOMParser().parseFromString(response.data, "text/xml"));
// get all <content> elements
me.courseElementContent = doc.querySelectorAll("content");
});
}
}
});
What am I missing? What should be changed to always reflect the correct value? (Note: I want to use a references data property to easily change "value" just by setting it.)
Thanks for enlightenment.
My interactive fiddle
https://jsfiddle.net/tvjquwmn/

Your data property is not reactive as it refer to a primitive type. It will indeed not be updated after the created step.
If you want it to be reactive, make it computed instead:
Vue.component('edit-element', {
template: `
<div>
<span v-html="direct ? xmlNode.firstChild.nodeValue : value"></span>
<span style="font-size: 60%; color:grey">({{ keyVal }})</span>
</div>`,
props: ["xmlNode", "keyVal", "direct"],
computed: {
value() {
return this.xmlNode.firstChild.nodeValue;
}
}
});
See working fiddle: https://jsfiddle.net/56c7utvc/

Related

Vuejs - How to set the default value of a prop to a predefined data?

The question is simple. I want to define a data as follows;
data() {
return {
logoURL: "some-link/some-picture.png"
}
}
and I want to set it to a prop's default state like this:
props: {
infoLogoURL: {
type: String,
default: this.logoURL,
},
}
Apparently it doesn't work the way I want and I have this error:
Uncaught TypeError: Cannot read property 'logoURL' of undefined
How can I manage this? Here is an example of how I use my props:
<cardComp
infoTitle = "Info Title"
infoText = "Info Text"
infoSubIcon = "Sub Icon Name"
infoSubIconColor = "css-color-class"
infoSubText = "Sub Text"
infoDescription = "Some Text Description"
infoIcon = "Icon Name"
infoIconColor = "icon-color-css"
infoLogoURL = "some-link/some-picture.png"
/>
And here is another question... I want to display infoIcon when there is no infoLogoURL. So let's say the link of that specific .png file is not available in a moment of time, so in that case, I want to display the infoIcon. When the .png file is available, I should only display the infoLogoURL, not the infoIcon. How do I do that?
You can't set the default value of a prop from data.
One way around this is to use a computed property instead:
computed: {
defaultLogoURL: function() {
return this.infoLogoURL || this.logoURL
}
}
You can define a computed property that returns the value of the prop "info_logo_url" when set, and that of data "logoURL" when not.
Concerning the second part of the question, another computed property can be defined to return the prop "info_logo_url" when set, and that of the prop "info_icon" when not.
const cardcomponent = Vue.component('card-component', {
template: '#card-component',
data(){
return { logoURL: "some-link/some-picture.png" }
},
props: {
info_logo_url: { type: String },
info_icon: { type: String }
},
computed: {
myInfoLogo() { return this.info_logo_url || this.logoURL; },
myInfoIcon() { return this.info_logo_url || this.info_icon; },
}
});
new Vue({
el: '#app',
components: { cardcomponent },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<cardcomponent info_logo_url="info logo URL" info_icon="info icon"/>
</div><hr>
<div>
<cardcomponent info_logo_url="info logo URL"/>
</div><hr>
<div>
<cardcomponent info_icon="info icon"/>
</div>
</div>
<template id="card-component">
<div>
<b>myInfoLogo</b>: {{myInfoLogo}} - <b>myInfoIcon</b>: {{myInfoIcon}}
</div>
</template>

Replace tag dynamically returns the object instead of the contents

I'm building an chat client and I want to scan the messages for a specific tag, in this case [item:42]
I'm passing the messages one by one to the following component:
<script>
import ChatItem from './ChatItem'
export default {
props :[
'chat'
],
name: 'chat-parser',
data() {
return {
testData: []
}
},
methods : {
parseMessage(msg, createElement){
const regex = /(?:\[\[item:([0-9]+)\]\])+/gm;
let m;
while ((m = regex.exec(msg)) !== null) {
msg = msg.replace(m[0],
createElement(ChatItem, {
props : {
"id" : m[1],
},
}))
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
}
return msg
},
},
render(createElement) {
let user = "";
let msg = this.parseMessage(this.$props.chat.Message, createElement)
return createElement(
'div',
{
},
[
// "hello",// createElement("render function")
createElement('span', '['+ this.$props.chat.Time+'] '),
user,
msg,
]
)
}
};
</script>
I thought passing createElement to the parseMessage method would be a good idea, but it itsn't working properly as it replaces the tag with [object object]
The chatItem looks like this :
<template>
<div>
<span v-model="item">chatITem : {{ id }}</span>
</div>
</template>
<script>
export default {
data: function () {
return {
item : [],
}
},
props :['id'],
created() {
// this.getItem()
},
methods: {
getItem: function(){
obj.item = ["id" : "42", "name": "some name"]
},
},
}
</script>
Example :
if the message looks like this : what about [item:42] OR [item:24] both need to be replaced with the chatItem component
While you can do it using a render function that isn't really necessary if you just parse the text into a format that can be consumed by the template.
In this case I've kept the parser very primitive. It yields an array of values. If a value is a string then the template just dumps it out. If the value is a number it's assumed to be the number pulled out of [item:24] and passed to a <chat-item>. I've used a dummy version of <chat-item> that just outputs the number in a <strong> tag.
new Vue({
el: '#app',
components: {
ChatItem: {
props: ['id'],
template: '<strong>{{ id }}</strong>'
}
},
data () {
return {
text: 'Some text with [item:24] and [item:42]'
}
},
computed: {
richText () {
const text = this.text
// The parentheses ensure that split doesn't throw anything away
const re = /(\[item:\d+\])/g
// The filter gets rid of any empty strings
const parts = text.split(re).filter(item => item)
return parts.map(part => {
if (part.match(re)) {
// This just converts '[item:24]' to the number 24
return +part.slice(6, -1)
}
return part
})
}
}
})
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<template v-for="part in richText">
<chat-item v-if="typeof part === 'number'" :id="part"></chat-item>
<template v-else>{{ part }}</template>
</template>
</div>
If I were going to do it with a render function I'd do it pretty much the same way, just replacing the template with a render function.
If the text parsing requirements were a little more complicated then I wouldn't just return strings and numbers. Instead I'd use objects to describe each part. The core ideas remain the same though.

Filtering a list of objects in Vue without altering the original data

I am diving into Vue for the first time and trying to make a simple filter component that takes a data object from an API and filters it.
The code below works but i cant find a way to "reset" the filter without doing another API call, making me think im approaching this wrong.
Is a Show/hide in the DOM better than altering the data object?
HTML
<button v-on:click="filterCats('Print')">Print</button>
<div class="list-item" v-for="asset in filteredData">
<a>{{ asset.title.rendered }}</a>
</div>
Javascript
export default {
data() {
return {
assets: {}
}
},
methods: {
filterCats: function (cat) {
var items = this.assets
var result = {}
Object.keys(items).forEach(key => {
const item = items[key]
if (item.cat_names.some(cat_names => cat_names === cat)) {
result[key] = item
}
})
this.assets = result
}
},
computed: {
filteredData: function () {
return this.assets
}
},
}
Is a Show/hide in the DOM better than altering the data object?
Not at all. Altering the data is the "Vue way".
You don't need to modify assets to filter it.
The recommended way of doing that is using a computed property: you would create a filteredData computed property that depends on the cat data property. Whenever you change the value of cat, the filteredData will be recalculated automatically (filtering this.assets using the current content of cat).
Something like below:
new Vue({
el: '#app',
data() {
return {
cat: null,
assets: {
one: {cat_names: ['Print'], title: {rendered: 'one'}},
two: {cat_names: ['Two'], title: {rendered: 'two'}},
three: {cat_names: ['Three'], title: {rendered: 'three'}}
}
}
},
computed: {
filteredData: function () {
if (this.cat == null) { return this.assets; } // no filtering
var items = this.assets;
var result = {}
Object.keys(items).forEach(key => {
const item = items[key]
if (item.cat_names.some(cat_names => cat_names === this.cat)) {
result[key] = item
}
})
return result;
}
},
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<button v-on:click="cat = 'Print'">Print</button>
<div class="list-item" v-for="asset in filteredData">
<a>{{ asset.title.rendered }}</a>
</div>
</div>

vue.js: Tracking currently selected row

I have a simple table where I would like to handle click elements:
<div class="row"
v-bind:class="{selected: isSelected}"
v-for="scanner in scanners"
v-on:click="scannerFilter">
{{scanner.id}} ...
</div>
JS:
new Vue({
el: "#checkInScannersHolder",
data: {
scanners: [],
loading: true
},
methods: {
scannerFilter: function(event) {
// isSelected for current row
this.isSelected = true;
// unselecting all other rows?
}
}
});
My problem is unselecting all other rows when some row is clicked and selected.
Also, I would be interested to know, it it is possible accessing the scanner via some variable of the callback function instead of using this as I might need to access the current context.
The problem is you have only one variable isSelected using which you want to control all the rows. a better approach will be to have variable: selectedScanner, and set it to selected scanner and use this in v-bind:class like this:
<div class="row"
v-bind:class="{selected: selectedScanner === scanner}"
v-for="scanner in scanners"
v-on:click="scannerFilter(scanner)">
{{scanner.id}} ...
</div>
JS
new Vue({
el: "#checkInScannersHolder",
data: {
scanners: [],
selectedScanner: null,
loading: true
},
methods: {
scannerFilter: function(scanner) {
this.selectedScanner = scanner;
}
}
});
I was under the impression you wanted to be able to selected multiple rows. So here's an answer for that.
this.isSelected isn't tied to just a single scanner here. It is tied to your entire Vue instance.
If you were to make each scanner it's own component your code could pretty much work.
Vue.component('scanner', {
template: '<div class="{ selected: isSelected }" #click="toggle">...</div>',
data: function () {
return {
isSelected: false,
}
},
methods: {
toggle () {
this.isSelected = !this.isSelected
},
},
})
// Your Code without the scannerFilter method...
Then, you can do:
<scanner v-for="scanner in scanners"></scanner>
If you wanted to keep it to a single VM you can keep the selected scanners in an array and toggle the class based on if that element is in the array or not you can add something like this to your Vue instance.
<div
:class="['row', { selected: selectedScanners.indexOf(scanner) !== 1 }]"
v-for="scanner in scanners"
#click="toggle(scanner)">
...
</div>
...
data: {
return {
selectedScanners: [],
...
}
},
methods: {
toggle (scanner) {
var scannerIndex = selectedScanners.indexOf(scanner);
if (scannerIndex !== -1) {
selectedScanners.splice(scannerIndex, 1)
} else {
selectedScanners.push(scanner)
}
},
},
...

Why value doesn't updated correctly in Vue when using v-for?

I've created basic jsfiddle here.
var child = Vue.component('my-child', {
template:
'<div> '+
'<div>message: <input v-model="mytodoText"></div> <div>todo text: {{todoText}}</div>'+
'<button #click="remove">remove</button>' +
'</div>',
props:['todoText'],
data: function(){
return {
mytodoText: this.todoText
}
},
methods: {
remove: function(){
this.$emit('completed', this.mytodoText);
}
}
});
var root = Vue.component('my-component', {
template: '<div><my-child v-for="(todo, index) in mytodos" v-bind:index="index" v-bind:todoText="todo" v-on:completed="completed"></my-child></div>',
props:['todos'],
data: function(){
return {
mytodos: this.todos
}
},
methods: {
completed: function(todo){
console.log(todo);
var index = this.mytodos.indexOf(todo, 0);
if (index > -1) {
this.mytodos.splice(index, 1);
}
}
}
});
new Vue({
el: "#app",
render: function (h) { return h(root, {
props: {todos: ['text 1', 'text 2', 'text 3']}
});
}
});
Code is simple: root component receives array of todos (strings), iterates them using child component and pass some values through the props
Click on the top "remove" button and you will see the result - I'm expecting to have
message: text 2 todo text: text 2
but instead having:
message: text 1 todo text: text 2
From my understanding vue should remove the first element and leave the rest. But actually I have some kind of "mix".
Can you please explain why does it happen and how it works?
This is due to the fact that Vue try to "reuse" DOM elements in order to minimize DOM mutations. See: https://v2.vuejs.org/v2/guide/list.html#key
You need to assign a unique key to each child component:
v-bind:key="Math.random()"
where in real-world the key would be for example an ID extracted from a database.