Vue: Render component differently, depending on parent components - vuejs2

I have multiple variants of cards in my app. Each card contains common sub-components (text blocks, avatars, images)
I want to assign specific css classes to a component when it is a sibling (not necessary a direct child) of specific card component.
Or add some html wrapper elements when component is rendered in specific card.
What is a recommended way to achieve this?
Or must one create different components for each card variant?

So i believe you have a card component which has some common components and these components needs to look different in different cases.
for example let me assume these cards will hold user details which is their avatar image, his/her name which can be editable etc. now these cards are required should look different for men and women
Approach 1 - adding classes:
Vue.component('my-card', {
props: {
cardType: String,
},
data: function(){
return {
menCardClasses: {
input: {'some-class': true}
},
womenCardClasses: {
input: {'other-class': true}
},
inputClasses: {}
}
},
computed: {
if(this.cardType == 'men'){
this.inputClasses = this.menCardClasses.input;
}
},
template: `<div class='card'><input :class="inputClasses"></div>`
});
In this approach your card component will deal with state and the classes child components get
Approach 2 - wrapper component:
Vue.component('my-card', {
props: {
cardType: String,
},
data: function(){
},
computed: {
},
template: `<div class='card'>
<men-card-component v-if="cardType=='men'"></men-card-component>
<women-card-component v-else></women-card-component>
</div>`
});
Vue.component('men-card-component', {
template: `<div class='men-card'><input /></div>`
});
Vue.component('women-card-component', {
template: `<div class='women-card'><input /></div>`
});
In this approach card component is just a wrapper which will render the another component based on the state.
You can pick the approach which suits you and make you feel comfortable.

Related

Parent component updates a child component v-for list, the new list is not rendered in the viewport (vue.js)

My app structure is as follows. The Parent app has an editable form, with a child component list placed at the side. The child component is a list of students in a table.
I'm trying to update a child component list. The child component uses a 'v-for', the list is generated through a web service call using Axios.
In my parent component, I am editing a students name, but the students new name is not reflected in the List that I have on screen.
Example:
Notice on the left the parent form has the updated name now stored in the DB. However, the list (child component) remains unchanged.
I have tried a few things such as using props, ref etc. I am starting to think that my app architecture may be incorrect.
Does anyone know how I might go about solving this issue.
Sections of the code below. You may understand that I am a novice at Vue.
Assistance much appreciated.
// Child component
<component>
..
<tr v-for="student in Students.slice().reverse()" :key="student._id">
..
</component>
export default {
env: '',
// list: this.Students,
props: {
inputData: Boolean,
},
data() {
return {
Students: [],
};
},
created() {
// AXIOS web call...
},
};
// Parent component
import List from "./components/students/listTerms";
export default {
name: "App",
components: {
Header,
Footer,
List,
},
};
// Implementation
<List />
I think that it is better to use vuex for this case and make changes with mutations. Because when you change an object in the data array, it is not overwritten. reactivity doesn't work that way read more about it here
If your list component doesn't make a fresh API call each time the form is submitted, the data won't reflect the changes. However, making a separate request each time doesn't make much sense when the component is a child of the form component.
To utilise Vue's reactivity and prevent overhead, it would be best to use props.
As a simplified example:
// Child component
<template>
...
<tr v-for="student in [...students].reverse()" :key="student._id">
...
</template>
<script>
export default {
props: {
students: Array,
},
};
</script>
// Parent component
<template>
<div>
<form #submit.prevent="submitForm">
<input v-model="studentData.name" />
<input type="submit" value="SUBMIT" />
</form>
<List :students="students" />
</div>
</template>
<script>
import List from "./components/students/listTerms";
export default {
name: "App",
components: {
List,
},
data() {
return {
students: [],
studentData: {
name: ''
}
}
},
methods: {
submitForm() {
this.$axios.post('/endpoint', this.studentData).then(() => {
this.students.push({ ...this.studentData });
}).catch(err => {
console.error(err)
})
}
}
};
</script>
Working example.
This ensures data that isn't stored successfully won't be displayed and data that is stored successfully reflects in the child component.

Vue - How to pass and use dynamically multiple components as props

I'm using AgGrid as the grid to show the data in the site.
Following this example Example: Rendering using VueJS Components, I'm able to use different components to be rendered into different columns.
Now that I need to implement this grid in multiple views, I want to make a "custom component" that implements the ag-grid-vue component, and receives just the column definitions, row data and components (if the columns are rendering another component).
Something like this:
<template>
<div>
<ag-grid-vue
:animateRows="true"
:columnDefs="columnDefs"
:frameworkComponents="frameworkComponents"
:defaultColDef="defaultColDef"
:gridOptions="gridOptions"
:pagination="true"
:paginationPageSize="paginationPageSize"
:rowData="rowData"
:suppressPaginationPanel="true"
colResizeDefault="shift"
ref="agGridTable"
rowSelection="multiple"
></ag-grid-vue>
</div>
</template>
<script>
import { AgGridVue } from "ag-grid-vue";
export default {
name: "AgGrid",
components: { AgGridVue },
props: ['columnDefs', 'components', 'rowData'],
data() {
return {
gridApi: null,
gridOptions: {},
defaultColDef: {
sortable: true,
resizable: true,
suppressMenu: true
},
frameworkComponents: null
}
},
beforeMount() {
this.frameworkComponents = this.components;
}
}
</script>
Now the parent will pass all the data needed:
<ag-grid :column-defs="columnDefs" :components="frameworkComponents" :row-data="gridList"></ag-grid>
The problem comes when I try to pass these components as props:
this.frameworkComponents = {
squareRenderer: SquareRenderer,
cubeRenderer: CubeRenderer,
paramsRenderer: ParamsRenderer,
currencyRenderer: CurrencyRenderer,
childMessageRenderer: ChildMessageRenderer,
};
Obviously, my custom component doesn't know these components because they are not imported, so the view could not find those components. Since each view will display diferent columns, and these one could or not display renderer components, I need to pass all the components needed to the grid component and import them.
Any ideas how to import and use those components?

How to pass editable data to component?

I'm working on an app that allows you to capture and edit soccer match results.
there is a Matches component that makes an AP call to get the data of multiple matches from a server (match_list) and then renders a bunch of Match components, passing the data as props to these sub-components to fill their initial values.
<component :is="Match" v-for="match in match_list"
v-bind:key="match.id"
v-bind="match"></component>
On the Match component, I accept all the values as props.
But I get a warning that props shouldn't be edited and these should be data elements instead. So I tried passing them to the component data.
export default {
name: "Match",
props: ['local_team', 'visitor_team', 'localScore', 'visitorScore', 'date', 'time', 'location', 'matchId'],
data(){
return{
id: this.id,
local_team: this.local_team,
visitor_team: this.visitor_team,
location: this.location,
date: this.date,
time: this.time,
localScore: this.localScore,
visitorScore: this.visitorScore
}
},
Now I get a warning that editable data shouldn't be based on props.
How can I make the data from the Match component editable so it safely propagates to the parent component?
You need to accept your match object on the component's props, and make a copy of it on data (to be used as a model for your inputs). When your model changes you should emit that change to the parent so that it can change its own data appropriately (which then gets passed and reflected correctly through the child's props):
In this example I watch for any changes to the model and then emit the event directly, you can of course replace that behavior by having a submit button that fires the event upon click or something.
Vue.component('match', {
template: `
<div>
<p>{{match.name}}</p>
<input v-model="matchModel.name" />
</div>
`,
props: ['match'],
data() {
return {
matchModel: Object.assign({}, this.match)
}
},
watch: {
matchModel: {
handler(val) {
this.$emit('match-change', val)
},
deep: true,
}
}
});
new Vue({
el: "#app",
data: {
matches: [{
id: 1,
name: 'first match'
},
{
id: 2,
name: 'second match'
}
]
},
methods: {
onMatchChange(id, newMatch) {
const match = this.matches.find((m) => m.id == id);
Object.assign(match, newMatch);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<match v-for="match in matches" :match="match" :key="match.id" #match-change="onMatchChange(match.id, $event)"></match>
</div>

Setting props of child component in vue

I'm following the example here of using a Vue template as a Kendo UI template in their components:
https://www.telerik.com/kendo-vue-ui/components/framework/vue-templates/
The example isn't very clear on how to supply properties to components that are rendered with this method (as opposed to rendering right in the template). I need to supply a single value determined in the parent to all instances of this child component, and I also need to subscribe to emitted events from the child component. My assumption is that there's an overload to Vue.component() that lets me access this functionality?
Edit:
Specifically what I am looking for is a way to have a header template for each column created from a Vue component. I need each column's template to receive data from the parent so I know how to construct it, and I also need each column's template to report an event back to the parent.
I think the key point is Step 3 in the link you attached (Kendo Vue Template Usage). (Never touch Kendo Before, if anything wrong, correct me, thanks.)
First, please open this Vue kendo Sandbox, you will find one dropdownlist then each option is one button plus one text. If you click the button, it will call one method in MyTemplate.vue and another Method at DropDownStyle.vue, then its background of each option is blue which passed from DropDownStyle.vue.
Kendo will bind this function of Step 3 to its attribute=template, then fisrt parameter (and only one) is each element of the data-source.
Then this function need to return one object including template and templateArgs, then Kendo construct it.
So my solution is add your function/callback/styles into templateArgs, then do what you need at MyTemplate.vue.
Below is the codes extended from Step 3.
methods: {
getMyTemplate: function (e) {
// parameter=e: it is the value of each element of the dropdown
e.callback = this.eventCallback
e.styles="background-color:blue"
return {
template: MyTemplate,
templateArgs: e
}
},
eventCallback: function (data) {
console.log(this.dropdowns)
}
}
Below is MyTemplate.vue.
<template>
<span :style="templateArgs.styles">
<button #click="buttonClick();templateArgs.callback()">{{templateArgs.value}}</button>
{{templateArgs.text}}
</span>
</template>
<script>
export default {
name: 'template1',
methods: {
buttonClick: function (e) {
console.log('props',this.templateArgs.styles)
}
},
data () {
return {
templateArgs: {
callback:function(){
console.log('Test')
},
styles:''
}
}
}
}
</script>
Very odd design choice in terms of passing the template in like they do. Avoiding the KendoUI and focusing on VueJS methods - could you use provide/inject? Providing the value in the parent and injecting in any of the children?
Also a plugin could be created to keep track of events or values you want available to all components in the application. In essence the plugin would be a service. A singleton object that is only instantiated once.
The documentation is indeed lacking. I agree with you on that. I took a different approach with templating for Kendo UI component and got this working: https://codesandbox.io/s/github/ariellephan/vue-kendoui-template
To start, I have this dropdown component that utilizes Kendo dropdown list component:
<template>
<div>
<p>Style with template {{template}}</p>
<kendo-dropdownlist
:template="template"
:headerTemplate="headerTemplate"
:data-source="dataSourceArray"
:data-text-field="'text'"
:data-value-field="'value'"
:filter="'contains'">
</kendo-dropdownlist>
</div>
</template>
<script>
export default {
name: "Dropdown",
props: ["dataSourceArray", "template", "headerTemplate"],
data() {
return {
value: "Click Me",
text: "I'm in Template template"
};
}
};
</script>
To render different styles/templates, I parsed in props from the parent component. In this case, DropdownStyles
<template>
<div id="DropdownStyles">
<h1>KendoUI dropdown instances with different templates</h1>
<Dropdown
v-for="dropdown in dropdowns"
v-bind:key="dropdown.id"
v-bind:title="dropdown.title"
v-bind:data-source-array="dropdown.dataSourceArray"
v-bind:template="dropdown.template"
v-bind:headerTemplate="dropdown.headerTemplate"
></Dropdown>
</div>
</template>
<script>
import Dropdown from "./Dropdown";
import DropdownTemplate from "./DropdownTemplate";
export default {
name: "DropdownStyles",
components: { Dropdown },
data() {
return {
dropdowns: [
{
id: 1,
title: "x style",
dataSourceArray: [
"Football",
"Tennis",
"Basketball",
"Baseball",
"Cricket",
"Field Hockey",
"Volleyball"
],
template: `<strong class="custom-dropdown">x #:data#</strong>`,
headerTemplate: DropdownTemplate.template
},
{
id: 2,
title: "+ style",
dataSourceArray: [
"Football",
"Tennis",
"Basketball",
"Baseball",
"Cricket",
"Field Hockey",
"Volleyball"
],
template: `<strong class="custom-dropdown">+ #:data#</strong>`,
headerTemplate: `<div><h3 style="padding-left:10px;">Sports 2</h3></div>`
}
]
};
}
};
</script>
You can move the template into its own file or function. For example, the first drop down is using DropdownTemplate for its headerTemplate:
DropdownTemplate.vue
<script>
export default {
name: "DropdownTemplate",
props: ["header"],
template: `<div>
<div><h3>Sports 1</h3></div>
</div>`,
data() {
return {};
}
};
</script>
<style scoped>
h3 {
padding-left: 10px;
}
</style>

Vue.js passing events up to parents in components

I have a Vue app like this:
<div id="example">
<event-emitting-component #clicked="methodOnRootInstance"></event-emitting-component>
<event-emitting-component-parent></event-emitting-component-parent>
<div v-for="click in clicks">
{{ click }}
</div>
</div>
And here is the JS for it:
// Child
Vue.component('event-emitting-component', {
template: '<div class="event-emitting-component" #click="$emit(\'clicked\')">Event emitter</div>'
});
// Parent
Vue.component('event-emitting-component-parent', {
template: '<div class="event-emitting-component-parent">' +
'A custom parent!'+
'<event-emitting-component></event-emitting-component>' + // <-- Please note child component
'</div>'
});
// create a root instance
new Vue({
el: '#example',
data: {
clicks : []
},
methods : {
methodOnRootInstance : function(){
this.clicks.push('Element clicked');
}
}
})
If you want to play with it it is also here:
https://codepen.io/EightArmsHQ/pen/QgbwPG?editors=1010
When you click the top child component a click is registered on the root element. Perfect.
When the child component is nested inside a parent (the second component in the example), obviously I can't add a #clicked="methodOnRootInstance" as that method doesn't exist inside the component.
What is the best way to pass an event up through a number of nested components?
I've made a stripped back example here, but in reality some components are two or three levels deep. Is the answer (what I think it is) that inside the parent component I would have the following:
Vue.component('event-emitting-component-parent', {
template: '<div class="event-emitting-component-parent">' +
'A custom parent!'+
'<event-emitting-component #clicked="passClicked"></event-emitting-component>' + // <-- Please note child component
'</div>',
'methods': {
passClicked : function(){
this.$emit('clicked')
}
}
});
And then in the html template add the same:
<event-emitting-component-parent #clicked="methodOnRootInstance"></event-emitting-component-parent>
I know I can get it to work like this, however it doesn't seem very elegant. I've looked in the docs and there are functions such as sync although I don't think it's what I need, I'm struggling to find the correct approach.
Bonus question: can vuex help with stuff like this?
This is the type of problem vuex is designed to solve, however, before you consider adding an extra layer of complexity to your app, you may be able to get away with a simple global event bus, which is simply an empty Vue object to emit events onto, which can then be listened for by any component in your app, bypassing the parent-child chain:
const bus = new Vue({});
Vue.component('comp-1', {
template: `<div>Comp 1 <button #click="emitClick">Click</button></div>`,
methods: {
emitClick(){
bus.$emit('comp-1-click');
}
}
})
Vue.component('comp-2', {
template: `<div><comp-1></comp-1></div>`,
})
new Vue({
el: '#app',
created(){
bus.$on('comp-1-click',() => {
console.log('Comp 1 clicked');
});
}
})
Here's the JSFiddle: https://jsfiddle.net/oatLhzLp/