Can't access sub-object in Vue JS 3 - javascript

I'm pretty new in VueJS and am stuck on the following problem:
I have a template in which a click on a button loads a new template through router.push and also sends an ID as data along.
The template:
<template>
<div>
{{ content.description }} // Works fine
{{ content.subobject.logo }} // Logo not found
</div>
</template>
In the new template that is being loaded I have the following function for saving the received ID into data:
created: function() {
this.ID = this.$route.params.data.toString()
},
then I have a function in methods which uses this ID to get data via axios/get:
methods: {
getContent: function() {
axios.get("https://api-url.com/" + this.ID)
.then((response) => {
this.content = response.data.data
console.log(response);
}).catch(error => {
console.log("ERRR:: ", error.response.data)
});
}
},
this function is called in mounted:
mounted: function() {
this.getContent()
}
My data function:
data: function() {
return {
ID: '',
content: [] as any
}
The data that is being returned by the API looks something like this:
title: "this is the title"
description: "Lorem Ipsum"
subobject: {
logo: "Logo URL"
}
When i use {{ content.title }} or {{ content.description }} in my template it shows up fine. As soon as I use {{ content.subobject.logo }} I'll get an error "logo" not found.
The funny thing is, when I have the template opend up and add the {{ content.subobject.logo }} after the page has loaded, save it, and it hot-reloads, it shows up fine?!
It seems like the data is not "available" on first load - but how can that be, if {{ content.title }} works fine?
Thanks a lot for any ideas!

The data is initially not available which means that content is still without inner field values, in order to avoid that add a conditional rendering like :
<div v-if="content.subobject">{{ content.subobject.logo }}</div>
you could also do :
data: function() {
return {
ID: '',
content: null
}
}
<template>
<template v-if="content">
<div >{{ content.subobject.logo }}</div>
<div >{{ content.title }}</div>
</template>
</template>

Related

how to v-model on different array vue 3

Hi I was trying to use a v-model an input to a value in object in an array of object in Vue 3. The complexity lies in the fact the object is first processed by a function. And that it need to be processed every time when a change is made to an input. Here is my code (and a sandbox link) :
<template>
<div id="app">
<div v-for="param in process(parameters)" :key="param">
Name : {{param.name}} Value : <input v-model="param.value">
</div>
{{parameters}}
</div>
</template>
<script>
export default {
name: "App",
data(){
return{
parameters :[
{'name':'Richard Stallman','value':'cool dude'},
{'name':'Linus Torvalds','value':'very cool dude'},
{'name':'Dennis Ritchie','value':'very very cool dude'}
]
}
},
methods:{
process(parameters){
const results = parameters.map( param =>{
return {name:param.name+' extra text',
value:param.value+' extra text',
}
})
return results
}
}
};
</script>
I just want the original parameters to change when something is types in the inputs. Maybe #change could be of use. But I didn't find a fix with #change. Does anyone know a solution to my problem? Thanks in advance.
Use computed property to get reactive state of the data.
Working Demo :
new Vue({
el: '#app',
data: {
parameters :[
{'name':'Richard Stallman','value':'cool dude'},
{'name':'Linus Torvalds','value':'very cool dude'},
{'name':'Dennis Ritchie','value':'very very cool dude'}
]
},
computed: {
process() {
const results = this.parameters.map((param) => {
return {
name: param.name + ' extra text',
value: param.value + ' extra text'
}
});
return results;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="param in process" :key="param">
Name : {{param.name}}
Value : <input v-model="param.value">
</div><br>
<strong>Orinigal Data :</strong> {{parameters}}
</div>
I am not entirely sure I understood whether the person should be able to see/edit the text you added within you processing method.
Anyway, I think this sample of code should solve you problem :
<template>
<div id="app">
<div v-for="param in parameters" :key="param.name">
Name : {{ param.name }} Value : <input v-model="param.value" />
</div>
{{ process }}
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
parameters: [
{ name: "Richard Stallman", value: "cool dude" },
{ name: "Linus Torvalds", value: "very cool dude" },
{ name: "Dennis Ritchie", value: "very very cool dude" },
],
};
},
computed: {
process: function() {
const results = this.parameters.map((param) => {
return {
name: param.name + " extra text",
value: param.value + " extra text",
};
});
return results;
},
},
};
</script>
So, we're iterating through the parameters array directly, adding an input on the value just like you did.
When you type in the input, you update the parameter linked to it, in live.
I just switched the method you made into a computed method.
This way, every time parameters is updated, "process" is also updated because it's depending on it directly.
I also removed passing the "parameters" argument, it's in the component data, you can just access it directly.
This way, using "process" just like any variable, you'll always have the updated parameters + what you added to em.

Vue.js return component value to vanilla javascript

I'm wondering if I am able to get a components data, the count property in this instance and console.log it into normal javascript, is this possible? I'm wanting to do console.log(btn.data.count) in this case
<div id="app" v-cloak>
<h1>{{greeting}}</h1>
<button-counter></button-counter>
</div>
<script src="https://unpkg.com/vue#next"></script>
<script>
let app = Vue.createApp({
data: function(){
return {
greeting: "hi"
}
}
})
let btn = app.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
console.log(btn.data.count) // doesn't work
app.mount("#app")
</script>
There might be multiple instances of the button-counter component, so you cannot ask for the count.
You can only access the data from within the component itself. For example from within a method that handles the click event:
let btn = app.component('button-counter', {
data: function () {
return {
count: 0
}
},
methods: {
onClick() {
console.log(this.count)
this.count++
}
},
template: '<button v-on:click="onClick">You clicked me {{ count }} times.</button>'
})
You can use console.log normally you just need to use it where it makes sense. It does not make sense using it before #app is mounted.
Try writing a method for your count++ and add console log there you will see that it gets executed every time.

Pass JS object to component Vue.js

I am having trouble displaying product via product component.
First in my vue.js app, I load Products via ajax like so:
var app = new Vue({
el: '#app',
data: {
products: [] // will be loaded via Ajax
},
mounted: function () {
var self = this;
ajaxGetProducts(0, self); // ajax, to fetch products
},
methods: {
getProducts: function (event) {
let groupID = Number(document.getElementById("GroupSelect").value);
ajaxGetProducts(groupID, this);
}
}
});
//Ajax call to fetch Products
function ajaxGetProducts(groupID, self) {
$.ajax({
type: "POST",
url: "/Data/GetProducts",
data: { Id: groupID },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json"
, success: function (response) {
self.products = response; // Loading products into the App instance
},
error: function (jqXHR, textStatus, errorThrown) {
self.products = [];
}
}).done(function () {
});
}
Then I display those produdcts, and it works just fine:
<!-- HTML -->
<div id="app">
<div v-for="prod in products" >{{prod.Id}}</div>
</div>
Question: if I want to use a component. How do I do that?
This is how my component looks so far:
Vue.component('product', {
props: [],
template: `<div>ProdID: {{product.Id}} {{product.Qty}}</div>`,
data() {
return {
Id: "test id"
}
}
})
Example Product object has following properties:
{
Id: 1,
Qty: 5,
Title: "Nike shoes",
Price: 200,
Color: "Green"
}
And eventually I would like to use it in HTML like so:
<!-- HTML -->
<div id="app">
<!-- need to pass prod object into product component -->
<div v-for="prod in products" >
<product></product>
</div>
</div>
I know that I have to pass the object via Component properties somehow?
Passing each property 1 by 1 is not a good idea, cause this product is subject to change, so property name can change, or be added more. I think there should be a way to pass a whole Product object to Product component somehow, right?
You can pass the information into your component via the props
something like this;
Vue.component('product', {
props: ['item'],
template: `<div>ProdID: {{item.Id}} {{item.Qty}}</div>`
})
and pass it on like this;
<div id="app">
<div v-for="prod in products" :key='prod.Id'>
<product :item='prod'></product>
</div>
</div>
What about passing it as
<product v-for="prod in products" :key="prod.Id" :product="prod"></product> and in the component: props: {product:{type: Object, required: true}}?
Then in the component template you can use things like {{product.Id}}

.Vue component not refreshing on each new message in laravel

I followed the following tutorial to create a chat application.
https://github.com/ammezie/laravel-chat
Every thing is right, messages are storing in db , showing on console in pusher desktop, all message show on page re load.
Problem is when i send a new message it not show in other user tab until i reload the page. I need to make it dynamic
following is the code for app.js where fetch function is written
created() {
this.fetchMessages();
Echo.private('chat')
.listen('MessageSent', (e) => {
this.messages.push({
message: e.message.message,
user: e.user
});
});
},
methods: {
fetchMessages() {
axios.get('/messages').then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.push(message);
axios.post('/messages', message).then(response => {});
}
here
Following is chat view code of component
<template>
<ul class="chat">
<li class="left clearfix" v-for="message in messages">
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">
{{ message.user.name }}
</strong>
</div>
<p>
{{ message.message }}
</p>
</div>
</li>
</ul>
</template>
<script>
export default {
props: ['messages']
};
</script>
Thanks for help if some thing unclear i'll provide
You can try.
methods: {
var vm = this;
fetchMessages() {
axios.get('/messages').then(response => {
vm.messages = response.data;
});
},
addMessage(message) {
var vm = this;
vm.messages.push(message);
axios.post('/messages', message).then(response => {});
}
using this inside function causing a problem, because it refers to that particular function create a global variable with reference to this
Hope this helps.
You may want to check if there are Laravel Echo credentials for pusher correct in bootstrap.js

Component Vuejs2 declare $data obj to share data between components

I am trying to make a Vue2 component to all the select of my app so would be easier later to change it if necessary!
I've based my research on the example given by the docs and I am breaking my head to figure out why should I speficy all the object on the data attr to make it work!
The following code is working properly, but if we change:
data: { record: { category_id: null } } by data: { record: {} } it stop to work!
Must be said the $data.record is loaded by ajax... would I always specify the whole object even knowing that after the ajax request I am going to replace all with something like this.record = response.data?
If somebody need there is FIDDLE [ https://jsfiddle.net/gustavobissolli/4xrfy54e/1/ ]
EDIT: SORRY GUYS JUST FIXED FIDDLE LINK
Vue.component('select2', {
props: ['options', 'value'],
template: '#select2-template',
data() {
return {
model: ''
}
},
mounted: function() {
this.model = this.value
},
watch: {
value: function(value) {
this.model = value
},
model: function(value) {
this.$emit('input', value)
},
}
})
var vm = new Vue({
el: '#el',
template: '#demo-template',
data: {
record: {
category_id: null
},
options: [{
id: 1,
text: 'Hello'
}, {
id: 2,
text: 'World'
}]
}
})
<div id="el"></div>
<!-- using string template here to work around HTML <option> placement restriction -->
<script type="text/x-template" id="demo-template">
<div>
<pre>{{ $data | json }}</pre>
<select2 :options="options" v-model="record.category_id" value="record.category_id"></select2>
</div>
</script>
<script type="text/x-template" id="select2-template">
<select v-model="model">
<option disabled>Select...</option>
<option v-for="opt in options" :value="opt.id">{{ opt.text }}</option>
</select>
</script>
So you are trying to edit a value which didn't arrive yet? :-)
The thing is: at the moment v-model="record.category_id" is "executed", you have nothing there, ie, there is no "category_id" at the "record" object. So, it binds to nothing. This is why the select won't work if you omit the "category_id" at data initialization.
But your assumption that when data arrives from server (ajax call) the component will not work, is wrong.
I have updated your fiddle: https://jsfiddle.net/4xrfy54e/4/
First, use the dropdown before clicking the button: since it is binded to nothing, it will not update anything. This is correct.
Now, click the button. The button is simulating that data arrived from the server, and is assigned to this.record of the vm.
Play with the dropdown again: since record.category_id exists now, the binding is working fine.
Please, read the "Reactivity in Depth" documentation page, and you will stop breaking your head :-)

Categories