VueJs - Passing data to subRoutes component with vue-router - vue.js

I don't understand how to pass data loaded by a 'route Component' to a 'subRoute Component'..
(I'm using Vue.js with Vue-router)
My router looks like that:
router.map({
'/a': {
component: A,
subRoutes: {
'/b': {
component: B
},
'/c': {
component: C
}
}
}
});
I just want to share data loaded by component A with component B and C.
Thanks in advance !

You have two simple options.
The ugly
Use the $parent option from the subroute components. That give you access to the parent instance, it's not the recommended way, but it's effective
// from the child component
this.$parent.someData
The good
Use props. Props give you the chance to pass any data from the parent to a child. It's better, because prevents error (you pass data not an instance) and you pass only what you need, even if it isn't part of the parent data.
// parent component
<template>
<child :childsdata="parentdata"></child>
</template
<script>
export default {
data: function () {
return {
parentdata: 'Hello!'
}
}
}
</script>
// child component
<template>
{{ childsdata }} <!-- prints "Hello!" -->
</template>
<script>
export default {
props: {
childsdata: {
type: String
}
}
}
</script>

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.

Pass data from blade to vue and keep parent-child in sync?

I know that in Vue parents should update the children through props and children should update their parents through events.
Assume this is my parent component .vue file:
<template>
<div>
<my-child-component :category="category"></my-child-component>
</div>
</template>
<script>
export default {
data: {
return {
category: 'Test'
}
}
}
</script>
When I update the category data in this component, it will also update the category props in my-child-component.
Now, when I want to use Vue in Laravel, I usually use an inline template and pass the value from the blade directly to my components (as for example also suggested at https://stackoverflow.com/a/49299066/2311074).
So the above example my my-parent-component.blade.php could look like this:
#push('scripts')
<script src="/app.js"></script>
#endpush
<my-parent-component inline-template>
<my-child-component :category="{{ $category }}"></my-child-component>
</my-parent-component>
But now my-parent-component is not aware about the data of category. Basically only the child knows the category and there is no communication between parent and child about it.
How can I pass the data from blade without breaking the parent and child communication?
I just had to pass the category to the inline-template component through props like this:
#push('scripts')
<script src="/app.js"></script>
#endpush
<my-parent-component :initcategory="{$category}}" inline-template>
<my-child-component v-model="category"></my-child-component>
</my-parent-component>
In my-parent-component I had to set the props and initialize is using the create method:
export default {
props: {
initcategory: '',
},
data() {
return {
category: '',
};
},
created(){
this.category = this.initcategory;
}
}
Now my my-parent-component is fully aware of the category and it can communicate to the child using props and $emit as usual.
Your reference to this answer is different altogether from what you are looking for!
He's binding the :userId prop of the example component but not the parent component or in simple words: Any template using the example vue can either pass a string prop or bind :userId prop to a string variable. Following is similar:
<example :userId="{{ Auth::user()->id }}"></example>
OR
<example :userId="'some test string'"></example>
So you should rather assign {{ $category }} to a data variable but rather binds to a child component prop which will have no effect on the parent.
In the following snippet you're only binding the string but rather a data key:
<my-child-component :category="{{ $category }}"></my-child-component>
Update
See the following example which will change the h1 title after 3 seconds
// HelloWorld.vue
<template>
<app-name :name="appName" #appNameChanged="appName = $event"></app-name>
</template>
<script>
export default {
props: ['name'],
data() {
return {
appName: null
}
},
mounted() {
// NOTE: since Strings are immutable and thus will assign the value while objects and arrays are copied by reference
// the following is just for the purpose of understanding how binding works
this.appName = this.name;
}
}
</script>
The template which renders the app title or you can say the child component
// AppName.vue
<template>
<h1>{{ name }}</h1>
</template>
<script>
export default {
props: ['name'],
mounted() {
setTimeout(() => {
this.$emit('appNameChanged', 'Change App')
}, 3000);
}
}
</script>
And here's how it is being used in the welcome.blade.php
<div id="app">
<hello-world :name="'Laravel App'"></hello-world>
</div>

Vuejs copy dynamic components methods

I am trying to make a visual representation of a component library. I am using dynamic <component>s to render each component. However, as I am populating the component with its slots, I am running into issues due to parent methods missing.
I want the components to be usable (demo) therefore I need to compensate for this.$parent not working.
<template>
<component v-bind:is="'s-' + comp.name" v-bind="props" ref="comp"> <!-- this is the corrent parent-->
<div v-if="comp.slots">
<div
v-for="(slot, i) in comp.slots"
v-bind:key="i"
v-bind:slot="slot.name"
>
<div v-if="slot.type == 'component'"> <!-- childs parent -->
<de-mo v-bind:comp="slot" /> <!-- this is the child calling a method on the parent -->
</div>
<div v-html="slot.value" v-else></div>
</div>
</div>
</component>
</template>
<script>
export default {
name: 'deMo',
computed: {
props() {
if (this.comp.props) {
return this.comp.props.reduce((a, r) => {
a[r.name] = r.value
return a
}, {})
}
}
},
props: {
comp: {
type: Object,
required: true
}
},
methods: this.$ref.comp.methods, //<-- this is an error
mounted(){
console.log(this.$ref.comp.methods)
}
},
</script>
<style></style>
1) Is there a way to copy the methods from the parent into this "demo" component via the ref attr
2) Alternatively, is there a better method to produce the same results?
Thanks
you can try to spread parent methods in a beforeCreate lifecycle as at this point your parent will be created and your component is going to register its all methods,
beforeCreate() {
this.$options.methods = { ...this.$parent.$options.methods };
},
however you can not access any refs in this as refs are only registered after mount of the component.
Note: Any library should use provide and inject to communicate with their component instead of referencing the parent component directly.
You can use an Event bus to communicate between components that aren't directly related to each other. Also, this is the recommended way of communication from child to parent in Vue.
bus.js
import Vue from 'vue'
export default new Vue()
demo.vue // child component that wants to call a method in the parent
import Bus from './bus.js'
export default {
mounted () {
// [1] child component will emit an event in the bus when it want to call a method of parent
Bus.$emit('invoke-parent-fn', 'param')
}
}
parent.vue // parent component where you want to render other components dynamically
import Bus from './bus.js'
export default {
methods: {
fn (param) {
console.log('// do something ' + param)
}
},
mounted () {
// [2] parent will be listening to the bus event, when child will emit an event, the handler passed in to the listener will be invoked
// [3] invoke the required method in the handler
Bus.$on('invoke-parent-fn', param => this.fn(param))
}
}

How to bind a local component's data object to an external component

how do you use a local component's data attriutes to bind an external component's v-model
for example i have this component
<publish-blog>
<VueTrix v-model="form.editorContent">
</publish-blog>
so the form.editorContent there refers to the publish-blog component's form.editorContent inside data, how do I do that ?
You can pass a prop to the publish-blog component.
This would be what ever page or component you are using the publish blog on, though to be honest I'm not sure why you would not just put the VueTrix component inside of the publish-blog component.
This would be on what ever page/component you are wanting it on.
<template>
<PublishBlog :trix="trix">
<VueTrix v-model="trix" />
</PublishBlog>
</template>
<script>
import PublishBlog from './PublishBlog.vue';
export default {
components: {
PublishBlog,
},
data() {
return {
trix: '',
};
},
};
</script>
and inside of the publish blog component make the form.editorContent the prop passed or a default value.
But without a global store/state you are stuck with props.
UPDATE: Showing what a publish blog component might look like
PublishBlog.vue
<template>
<section>
what ever goes here.
<slot />
</section>
</template>
<script>
export default {
name: 'PublishBlog',
props: {
trix: {
type: String,
default: '',
},
},
data() {
return {
form: {
editorContent: this.trix
},
};
},
};
</script>

Vue best practice for calling a method in a child component

I have been reading lots of articles about this, and it seems that there are multiple ways to do this with many authors advising against some implementations.
To make this simple I have created a really simple version of what I would like to achieve.
I have a parent Vue, parent.vue. It has a button:
<template>
<div>
<button v-on:click="XXXXX call method in child XXXX">Say Hello</button>
</div>
</template>
In the child Vue, child.vue I have a method with a function:
methods: {
sayHello() {
alert('hello');
}
}
I would like to call the sayHello() function when I click the button in the parent.
I am looking for the best practice way to do this. Suggestions I have seen include Event Bus, and Child Component Refs and props, etc.
What would be the simplest way to just execute the function in my method?
Apologies, this does seem extremely simple, but I have really tried to do some research.
Thanks!
One easy way is to do this:
<!-- parent.vue -->
<template>
<button #click="$refs.myChild.sayHello()">Click me</button>
<child-component ref="myChild" />
</template>
Simply create a ref for the child component, and you will be able to call the methods, and access all the data it has.
You can create a ref and access the methods, but this is not recommended. You shouldn't rely on the internal structure of a component. The reason for this is that you'll tightly couple your components and one of the main reasons to create components is to loosely couple them.
You should rely on the contract (interface in some frameworks/languages) to achieve this. The contract in Vue relies on the fact that parents communicate with children via props and children communicate with parents via events.
There are also at least 2 other methods to communicate when you want to communicate between components that aren't parent/child:
the event bus
vuex
I'll describe now how to use a prop:
Define it on your child component
props: ['testProp'],
methods: {
sayHello() {
alert('hello');
}
}
Define a trigger data on the parent component
data () {
return {
trigger: 0
}
}
Use the prop on the parent component
<template>
<div>
<childComponent :testProp="trigger"/>
</div>
</template>
Watch testProp in the child component and call sayHello
watch: {
testProp: function(newVal, oldVal) {
this.sayHello()
}
}
Update trigger from the parent component. Make sure that you always change the value of trigger, otherwise the watch won't fire. One way of doing this is to increment trigger, or toggle it from a truthy value to a falsy one (this.trigger = !this.trigger)
I don't like the look of using props as triggers, but using ref also seems as an anti-pattern and is generally not recommended.
Another approach might be: You can use events to expose an interface of methods to call on the child component this way you get the best of both worlds while keeping your code somehow clean. Just emit them at the mounting stage and use them when pleased. I stored it in the $options part in the below code, but you can do as pleased.
Child component
<template>
<div>
<p>I was called {{ count }} times.</p>
</div>
</template>
<script>
export default {
mounted() {
// Emits on mount
this.emitInterface();
},
data() {
return {
count: 0
}
},
methods: {
addCount() {
this.count++;
},
notCallable() {
this.count--;
},
/**
* Emitting an interface with callable methods from outside
*/
emitInterface() {
this.$emit("interface", {
addCount: () => this.addCount()
});
}
}
}
</script>
Parent component
<template>
<div>
<button v-on:click="addCount">Add count to child</button>
<child-component #interface="getChildInterface"></child-component>
</div>
</template>
<script>
export default {
// Add a default
childInterface: {
addCount: () => {}
},
methods: {
// Setting the interface when emitted from child
getChildInterface(childInterface) {
this.$options.childInterface = childInterface;
},
// Add count through the interface
addCount() {
this.$options.childInterface.addCount();
}
}
}
</script>
With vue 3 composition api you can do it like this:
Parent.vue
<script setup lang="ts">
const childRef = ref()
const callSayHello = () => {
childRef.value.sayHello()
}
</script>
<template>
<child ref="childRef"></child>
</template>
<style scoped></style>
Child.vue
<script setup lang="ts">
const sayHello = () => {
console.log('Hello')
}
defineExpose({ sayHello })
</script>
<template></template>
<style scoped></style>
I am not sure is this the best way. But I can explain what I can do...
Codesandbox Demo : https://codesandbox.io/s/q4xn40935w
From parent component, send a prop data lets say msg. Have a button at parent whenever click the button toggle msg true/false
<template>
<div class="parent">
Button from Parent :
<button #click="msg = !msg">Say Hello</button><br/>
<child :msg="msg"/>
</div>
</template>
<script>
import child from "#/components/child";
export default {
name: "parent",
components: { child },
data: () => ({
msg: false
})
};
</script>
In child component watch prop data msg. Whenever msg changes trigger a method.
<template>
<div class="child">I am Child Component</div>
</template>
<script>
export default {
name: "child",
props: ["msg"],
watch: {
msg() {
this.sayHello();
}
},
methods: {
sayHello() {
alert("hello");
}
}
};
</script>
This is an alternate take on Jonas M's excellent answer. Return the interface with a promise, no need for events. You will need a Deferred class.
IMO Vue is deficient in making calling child methods difficult. Refs aren't always a good option - in my case I need to call a method in one of a thousand grandchildren.
Parent
<child :getInterface="getInterface" />
...
export default {
setup(props) {
init();
}
async function init() {
...
state.getInterface = new Deferred();
state.childInterface = await state.getInterface.promise;
state.childInterface.doThing();
}
}
Child
export default {
props: {
getInterface: Deferred,
},
setup(props) {
watch(() => props.getInterface, () => {
if(!props.getInterface) return;
props.getInterface.resolve({
doThing: () => {},
doThing2: () => {},
});
});
}
}