Pass data object to component from Vue for loop - javascript

So i have some object with posts, and i'm using v-for to iterate them in the custom component, but how to pass data from this object to this component, loop is a one thing displaying data i another...
<app-single-post v-for="post in posts" postData="$post"></app-single-post>
This is my component declaration. Do i need also some kind of special prop setup? Have the same error, again and again:
Property or method "postData" is not defined

Use the binding syntax.
<app-single-post v-for="post in posts" :post="post" :key="post.id"></app-single-post>
Camel-cased properties need to be converted to kebab-case when they are used as attributes. Also, I added a key. You should always use a key when you use v-for and it is required when you iterate over a custom component. Ideally you would want to use a post.id if one is available.
In your component, you should have a property defined like this:
export default {
props:["post"],
methods: {...},
etc.
}
To reference the post in your component template you can use
{{post.id}}
and inside methods it would be
this.post

Related

Vue2 - Accessing to methods of a component with a generated ref name

I'm trying to access to a method of an child component, to validate multiple forms.
I have an array named "forms", each form object has a randomly generated id. Based on these form objects I generate components and give them a ref name
In my validateAll method I'm trying to loop over all forms, find components with their id as component's ref name. When I find the component (no problem so far), I try to call the child's method. But I get an error.
This is where I render components with v-for loop:
<SupportRequestForm v-for="(form, idx) in forms" :key="form.id"
...
:ref="`formRef${form.id}`"
/>
This is validateAll method, where I try to access child method:
validateAllForms() {
return this.forms.find(form => {
const formComponent = this.$refs[`formRef${form.id}`]
console.log(formComponent)
return formComponent.validateForm()
})
}
And this is the error:
I can access child component's method when it's a static ref name but I can't do the same thing when the is generated on the spot. Is this an expected behaviour or am I doing something wrong ?
Thank you very much in advance.
No need to bind each form to the form id, just create one ref called forms and since it's used with v-for it will contain the forms array :
When ref is used together with v-for, the ref you get will be an array containing the child components mirroring the data source
<SupportRequestForm v-for="(form, idx) in forms" :key="form.id" ref="forms" />
in method :
validateAllForms() {
this.$refs.forms.forEach(formComponent=> {
formComponent.validateForm()
})
}

vue - $emit vs. reference for updating parent data

We need to use $emit to update the parent data in a vue component. This is what has been said everywhere, even vue documentation.
v-model and .sync both use $emit to update, so we count them $emit here
what I'm involved with is updating the parent data using reference type passing
If we send an object or array as prop to the child component and change it in the child component, changes will be made to the parent data directly.
There are components that we always use in a specific component and we are not going to use them anywhere else. In fact, these components are mostly used to make the app codes more readable and to lighten the components of the app.
passing reference type values as prop to children for directly change them from children is much easier than passing values then handle emitted event. especially when there are more nested components
code readability is even easier when we use reference type to update parent.
For example, suppose we have grand-parent, parent and child components. in parent component we have a field that change first property of grand-parent data and in child component we have another field that change second property of grand-parent data
If we want to implement this using $emit we have something like this : (we are not using .sync or v-model)
// grand-parent
<template>
<div>
<parent :fields="fields" #updateFields="fields = $event" >
</div>
</template>
<script>
import parent from "./parent"
export default {
components : {parent},
data(){
return {
fields : {
first : 'first-value',
second : 'second-value',
}
}
}
}
</script>
// parent
<template>
<div>
<input :value="fields.first" #input="updateFirstField" />
<child :fields="fields" #updateSecondField="updateSecondField" >
</div>
</template>
<script>
import child from "./child"
export default {
components : {child},
props : {
fields : Object,
},
methods : {
updateFirstField(event){
this.$emit('updateFields' , {...this.fields , first : event.target.value})
},
updateSecondField(value){
this.$emit('updateFields' , {...this.fields , second : value})
}
}
}
</script>
// child
<template>
<div>
<input :value="fields.first" #input="updateSecondField" />
</div>
</template>
<script>
export default {
props : {
fields : Object,
},
methods : {
updateFirstField(event){
this.$emit('updateSecondField' , event.target.value)
},
}
}
</script>
Yes, we can use .sync to make it easier or pass just field that we need to child. but this is basic example and if we have more fields and also we use all fields in all component this is the way we do this.
same thing using reference type will be like this :
// grand-parent
<template>
<div>
<parent :fields="fields" >
</div>
</template>
<script>
import parent from "./parent"
export default {
components : {parent},
data(){
return {
fields : {
first : 'first-value',
second : 'second-value',
}
}
}
}
</script>
// parent
<template>
<div>
<input v-model="fields.first" />
<child :fields="fields" >
</div>
</template>
<script>
import child from "./child"
export default {
components : {child},
props : {
fields : Object,
}
}
</script>
// child
<template>
<div>
<input v-model="fields.second" />
</div>
</template>
<script>
export default {
props : {
fields : Object,
}
}
</script>
as you see using reference type is much easier. even if there was more fields.
now my question :
should we use reference type for updating parent data or this is bad approach ?
even if we use a component always in the same parent again we should not use this method ?
what is the reason that we should not use reference type to update parent?
if we should not use reference type why vue pass same object to children and not clone them before passing ? (maybe for better performance ?)
The "always use $emit" rule isn't set in stone. There are pros and cons of either approach; you should do whatever makes your code easy to maintain and reason about.
For the situation you described, I think you have justified mutating the data directly.
When you have a single object with lots of properties and each property can be modified by a child component, then having the child component mutate each property itself is fine.
What would the alternative be? Emitting an event for each property update? Or emitting a single input event containing a copy of the object with a single property changed? That approach would result in lots of memory allocations (think of typing in a text field emitting a cloned object for each keypress). Having said that, though, some libraries are designed for this exact purpose and work pretty well (like Immutable.js).
For simple components that manage only small data like a textbox with a single string value, you should definitely use $emit. For more complex components with lots of data then sometimes it makes sense for the child component to share or own the data it is given. It becomes a part of the child component's contract that it will mutate the data in certain circumstances and in some particular way.
what is the reason that we should not use reference type to update parent?
The parent "owns" the data and it knows that nobody but itself will mutate it. No surprises.
The parent gets to decide whether or not to accept the mutation, and can even modify it on-the-fly.
You don't need a watcher to know when the data is changed.
The parent knows how the data is changed and what caused the change. Imagine there are multiple ways that the data can be mutated. The parent can easily know which mutation originated from a child component. If external code (i.e. inside a child component) can mutate the data at any time and for any reason, then it becomes much more difficult for the parent to know what caused the data to change (who changed it and why?).
if we should not use reference type why vue pass same object to children and not clone them before passing ? (maybe for better performance ?)
Well yes, for performance, but also many other reasons such as:
Cloning is non-trivial (Shallow? Deep? Should the prototype be copied too? Does it even make sense to clone the object? Is it a singleton?).
Cloning is expensive memory- and CPU-wise.
If it were cloned then doing what you describe here would be impossible. It would be silly to impose such a restrictive rule.
#Vue Detailed usage of $refs, $emit, $on:
$refs - parent component calls the methods of the child component. You can pass data.
$emit - child components call methods of the parent component and pass data.
$on - sibling components pass data to each other.

Vue2 passing arbitrary named variable as prop

I am new to Vue and after checking the docs I can not figure out how to achieve the following:
pass an arbitrarily named variable as a prop to a component instance.
From my understanding, props are meant to be a way to allow data to be passed to a component and as it states on the website:
Passing Data to Child Components with Props:
Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
Since props can be required, it would seem that we can design components under the assumption that some data would be there, and possible within certain parameters (if the validator option is specified).
So I would like to define a function or object outside of vue, e.g. in an application, and pass this function or object to my vue instance.
This works if my named object of function has the exact same name as the prop to which I attempt to bind it. However, as I might have multiple instances of the Vue component and I might want to bind different data, I find using the same name for the variable less than ideal.
Now if I do as the Vue warning suggests, and name object / function the same as the prop, then the warning switches to that my data is not defined inside vue and to make sure it is reactive by reading: https://v2.vuejs.org/v2/guide/components-props.html
which, to be honest, doesnt really explain how to solve the issue,
or move the prop to the data level.
Which I can do (still gives the same warning), but kind of defeats the purpose of having props with my understanding of Vue.
This become more frustrating with anonymous vue instances.
e.g.
<script>
export default {
props: {
// records: {
// default: function(){return{}},
// type: Object
// }
},
data: function() {
return {
records: {} // define even an empty value in data for it to be 'reactive'
}
},
computed: {
fields: function() {
},
keys: function() {
return Object.keys(this.records)
}
},
methods: {
}
}
</script>
trying to use this as a component and set records to var myRecords = {"a": {}} fails:
<my-comp :records="myRecords"/>
So how exactly should I circumvent this? Where should I define my data then? and how should I handle the naming in the case of multiple instances?
A more fledged on example is found on a similar question:
Vue2: passing function as prop triggers warning that prop is already set
So I would like to define a function or object outside of vue, e.g. in an application, and pass this function or object to my vue instance.
It's hard to give a definitive answer because I don't know the specifics of how you have organized your code. Are you using Webpack? Single file components (.vue)? If yes to any of these, then you needn't use global variables in the way you have described in your question.
Your entire Vue app should consist of a single root Vue instance (which you instantiate with new Vue(...), and from there each component is rendered within the root component's template, and templates of those components, and so on.
Looking at the following template:
<my-comp :records="myRecords"/>
myRecords must be a property on the Vue component instance whose template contains the above. It could be declared within the data block, or as a computed property, or a prop, it doesn't matter.
Here's a small example:
<div id="app">
<my-comp :records="myRecords"></my-comp>
</div>
// Obtain records in some way and store it in a global variable
var records = ...
// This is the root Vue instance
new Vue({
el: '#app',
data: {
// You must store the records array in the Vue component like this
// for it to be referenced within the template.
// You can optionally transform the data first if you want.
myRecords: records.filter(r => r.name.startsWith('Bob'))
// ^ ^
// | |
// | +--- the global variable
// |
// +---- the name of the property on the component instance
}
})
Note that MyComp component does not access the records global variable in any way, it only takes its input through the records prop.

Can not get the value of id with vue $refs?

I see the about vue $ refs document, the console to see is {}, I do not know how to get the value of id?
There { } is no object, how to get $ refs id of value,but I think this {} not get to object.I try to use console.log(this.$refs.dataInfo.id) is undefined.
Look at the picture:
javascript file:
console.log(this.$refs)
HTML file:
<tab-item v-for="item in category" :id="item.id" ref="dataInfo">{{item.name}}</tab-item>
console.log(this.$refs.dataInfo.id) is undefined because you are trying to access an element's attribute through a reference to a component. Based on your example object, you can access it like this: this.$refs.dataInfo[0]['$el'].id
That's an odd way of doing it, I believe. The Vue way of doing it would be:
Using events. When props change in the child component and you want to do something about it in the parent component, you should emit a custom event. You'd do something like this in the child component: this.$emit('dataChange', data). And in the parent component add an event listener #dataChange="myMethod" to the component.
Using Vuex.
Having a good understanding of the basic concepts such as how the data flows in the application is a must and should not be overlooked!

Access key from child component in vue

According to Vue docs, binding a key is required to use custom components in a v-for:
<template v-for="(task,i) in tasks">
<task-card v-bind:task="task" v-bind:key="i"></task-card>
</template>
I would like to use that key in the child component (task-card), but neither using this.key or adding key as a prop (is a reserved Vue keyword) works. Is there a way of doing this without passing yet another prop with the value "i"? Currently working with "vue": "^2.5.9".
If you want to pass data to the child, you should be using props (key is reserved so you'll have to name it something else).
Otherwise you can access the key on the vnode within the component via this.$vnode.key.
Vue 3
For Vue 3 the API has changed. You will need to access the vnode from internal private instance like so: this.$.vnode.key. As far as I know this is undocumented and may change; use with caution.

Categories

Resources