VueJs how to get data from Vue.component - vuejs2

I want to know how to get data from Vue.component and send to
this >>var app = new Vue({ })<<
this is my code
Vue.component('my-form', {
template: '#my-form',
props:['ddTechtemp'],
data: function () {
return {
isCores: app.testCorres,
activeClass: 'isCorrespon',
errorClass: 'isTech',
tempData : {cell1 : "",
cell2 : "",
cell3 : "",
cell4 : "",
cell5 : "",
cell6 : ""
},
}
},
watch:{
tempData:{
handler:function(newVal,oldVal){
app.ddTechtemp = newVal;
},
deep:true,
}
},
methods:{
}});
I want to get data from above code and send to this code var app = new Vue({ data: Vue.component.data})
Anyone understand me please help.Thank you

In Vue.js parent-child relationship is run by
1) passing props from parent to child
2) emitting custom events from child to parent
So, if you need to pass some data from child to parent - use this.$emit to emit a custom event with your data, and listen for this event in parent component with v-on:myevent or #myevent shorthand. The data you pass with event is found in $event variable.
Example: https://jsfiddle.net/wostex/63t082p2/51/
<div id="app">
<myform #newdata="handleData($event)"></myform>
<p>name: {{ user.name }}</p>
<p>age: {{ user.age }}</p>
</div>
new Vue({
el: '#app',
data: {
user: { name: '', age: 0 }
},
methods: {
handleData: function(e) {
[this.user.name, this.user.age] = e;
}
},
components: {
'myform': {
template: `
<div>
<input type="text" v-model="formData.name" placeholder="Your name">
<input type="number" v-model.number="formData.age">
</div>`,
data: function() {
return { formData: { name: '', age: 0 } }
},
watch: {
formData: {
handler: function() {
this.$emit('newdata', [this.formData.name, this.formData.age]);
},
deep: true
}
}
}
}
});

Another way would be to work with advanced things like a Vuex store for ''state management'' but for simple implementations one additional reactive component would work as well.
in src/store/index.js
import { reactive } from 'vue';
export const store = reactive({
some_id : 0,
});
And in a component src/component/SelectComponent.vue
<script setup>
import { store } from "#/store";
</script>
<script>
export default {
name: "SelectComponent",
// rest of the component source here
}
</script>
<template>
<select v-model="store.some_id">
<option v-for="itm in list" :key=itm.id" :value="itm.id">{{ itm.text }}</option>
</select>
</template>
Using the component in src/views/SomeView.vue
<script setup>
import { store } from "#/store";
import SelectComponent from "#/components/SelectComponent"
</script>
<script>
//... use store.some_id in some method
</script>
You can store all your global variables in the store/index.js file and keep reactive. You might want to add watchers to observe the store variable(s).
WARNING: this is discouraged for large, complex Vue applications
NOTE: this is an easy approach for simple state management not requrring Vuex with all the actions and mutations, states and contexts - plumbing.

Related

Vue 3: Wait until parent is done with data fetching to fetch child data and show loader

I'm looking for a reusable way to display a full page loader (Sidebar always visible but the loader should cover the content part of the page) till all necessary api fetches has been done.
I've got a parent component LaunchDetails wrapped in a PageLoader component
LaunchDetails.vue
<template>
<PageLoader>
<router-link :to="{ name: 'launches' }"> Back to launches </router-link>
<h1>{{ name }}</h1>
<section>
<TabMenu :links="menuLinks" />
</section>
<section>
<router-view />
</section>
</PageLoader>
</template>
<script>
import TabMenu from "#/components/general/TabMenu";
export default {
data() {
return {
menuLinks: [
{ to: { name: "launchOverview" }, display_name: "Overview" },
{ to: { name: "launchRocket" }, display_name: "Rocket" },
],
};
},
components: {
TabMenu,
},
created() {
this.$store.dispatch("launches/fetchLaunch", this.$route.params.launch_id);
},
computed: {
name() {
return this.$store.getters["launches/name"];
},
},
};
</script>
PageLoader.vue
<template>
<Spinner v-if="isLoading" full size="medium" />
<slot v-else></slot>
</template>
<script>
import Spinner from "#/components/general/Spinner.vue";
export default {
components: {
Spinner,
},
computed: {
isLoading() {
return this.$store.getters["loader/isLoading"];
},
},
};
</script>
The LaunchDetails template has another router-view. In these child pages new fetch requests are made based on data from the LaunchDetails requests.
RocketDetails.vue
<template>
<PageLoader>
<h2>Launch rocket details</h2>
<RocketCard v-if="rocket" :rocket="rocket" />
</PageLoader>
</template>
<script>
import LaunchService from "#/services/LaunchService";
import RocketCard from "#/components/rocket/RocketCard.vue";
export default {
components: {
RocketCard,
},
mounted() {
this.loadRocket();
},
data() {
return {
rocket: null,
};
},
methods: {
async loadRocket() {
const rocket_id = this.$store.getters["launches/getRocketId"];
if (rocket_id) {
const response = await LaunchService.getRocket(rocket_id);
this.rocket = response.data;
}
},
},
};
</script>
What I need is a way to fetch data in the parent component (LaunchDetails). If this data is stored in the vuex store, the child component (LaunchRocket) is getting the necessary store data and executes the fetch requests. While this is done I would like to have a full page loader or a full page loader while the parent component is loading and a loader containing the nested canvas.
At this point the vuex store is keeping track of an isLoading property, handled with axios interceptors.
All code is visible in this sandbox
(Note: In this example I could get the rocket_id from the url but this will not be the case in my project so I'm really looking for a way to get this data from the vuex store)
Im introduce your savior Suspense, this feature has been added in vue v3 but still is an experimental feature. Basically how its work you create one suspense in parent component and you can show a loading when all component in any depth of your application is resolved. Note that your components should be an async component means that it should either lazily loaded or made your setup function (composition api) an async function so it will return an async component, with this way you can fetch you data in child component and in parent show a fallback if necessary.
More info: https://vuejs.org/guide/built-ins/suspense.html#suspense
You could use Events:
var Child = Vue.component('child', {
data() {
return {
isLoading: true
}
},
template: `<div>
<span v-if="isLoading">Loading …</span>
<span v-else>Child</span>
</div>`,
created() {
this.$parent.$on('loaded', this.setLoaded);
},
methods: {
setLoaded() {
this.isLoading = false
}
}
});
var Parent = Vue.component('parent', {
components: { Child },
data() {
return {
isLoading: true
}
},
template: `<div>
Parent
<Child />
</div>`,
mounted() {
let request1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
});
let request2 = new Promise((resolve, reject) => {
setTimeout(resolve, 2000);
});
Promise.all([ request1, request2 ]).then(() => this.$emit('loaded'))
}
});
new Vue({
components: { Parent },
el: '#app',
template: `<Parent />`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
This may be considered an anti-pattern since it couples the parent with the child and events are considered to be sent the other way round. If you don't want to use events for that, a watched property works just fine, too. The non-parent-child event emitting was removed in Vue 3 but can be implemented using external libraries.

Vue JS: vuex state not updating the component after change [duplicate]

This question already has answers here:
vuex store doesn't update component
(4 answers)
Closed 4 years ago.
I created an info-bar, an area I want to update with info from the component. I added it as a child of App.vue :
<template>
<div id="app">
<InfoBar /> // my info-bar
<router-view/>
</div>
</template>
To be able to update m<InfoBar /> from other components, I decided to try using Vuex and use mutations to change info:
Vuex Store:
export const store = new Vuex.Store({
state:{
infoBarText: "Text from Vuex store" , // initial text for debugging
},
mutations:{
setInfoBarText(state,text){
state.infoBarText = text;
}
}
infobar.vue
<template>
<div>
{{infoString}} // the result is always "Text from Vuex store"
</div>
</template>
<script>
export default {
name: "infoBar",
data() {
return {
infoString: this.$store.state.infoBarText
}
}
Now, I would like to update the text using the Vuex mutation from other component:
other.vue:
mounted() {
this.$store.commit("setInfoBarText", "Text from Component");
}
I checked the state of infoBarText with Vue developer tools and it successfully changed to "Text from Component" but it's not changed the text in the component.
What I am doing wrong?
You should be using computed instead of data, because data itself is not reactive once it is assigned. This will fix your issue:
export default {
name: "infoBar",
computed: {
infoString: function() {
return this.$store.state.infoBarText;
}
}
}
Proof-of-concept:
const infobar = Vue.component('infobar', {
template: '#infobar-template',
computed: {
infoString: function() {
return store.state.infoBarText;
}
}
});
const store = new Vuex.Store({
state: {
infoBarText: "Text from Vuex store", // initial text for debugging
},
mutations: {
setInfoBarText(state, text) {
state.infoBarText = text;
}
}
});
new Vue({
el: '#app',
methods: {
updateText() {
store.commit("setInfoBarText", "Text from Component");
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.22/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>
<div id="app">
<InfoBar></InfoBar>
<button #click="updateText">Update text</button>
</div>
<script type="text/x-template" id="infobar-template">
<div>
{{infoString}}
</div>
</script>

How do I make reactive global property in vuejs plugin?

I put $testCounter in a plugin to make it global :
Vue.use({
install(Vue) {
Vue.prototype.$testCounter = 0;
Vue.prototype.$incrementCounter = () => {
Vue.prototype.$testCounter++;
};
});
I want to output it in some component. I also need its value to be updated globally, and reactively :
<template>
<p>{{ $testCounter }}</p>
</template>
<script>
mounted() {
let comp = this;
comp.watcherId = setInterval(() => {
comp.$incrementCounter();
// I want to remove this line and still be reactive :
comp.$forceUpdate();
}, 1000);
}
</script>
I need the property to be reactive, I tried a multiple solution as watchers, computed props, vm.$set(...), but I can't find the right way to do this.
Solution 1: use Vuex
Solution 2: set the global reactive data in root component and use it by calling this.$root
demo: https://jsfiddle.net/jacobgoh101/mdt4673d/2/
HTML
<div id="app">
<test1>
{{$root.testCounter}}
</test1>
</div>
Javascript
Vue.component('test1', {
template: `
<div>
test1
<slot></slot>
</div>
`,
mounted() {
setInterval(() => {
this.$root.incrementCounter();
}, 1000)
}
});
new Vue({
el: "#app",
data: {
testCounter: 1
},
methods: {
incrementCounter: function() {
this.testCounter++;
}
}
})

vue.js wrapping components which have v-models

I have a 3rd party input component (a vuetify v-text-field).
For reasons of validation i prefer to wrap this component in my own.
my TextField.vue
<template>
<v-text-field
:label="label"
v-model="text"
#input="onInput"
#blur="onBlur"
:error-messages="this.getErrors(this.validation, this.errors)"
></v-text-field>
</template>
<script>
import VTextField from "vuetify/es5/components/VTextField";
import {vuelidateErrorsMixin} from '~/plugins/common.js';
export default {
name: "TextField",
props: ['label', 'value', 'validation', 'errors'],
mixins: [vuelidateErrorsMixin], //add vuelidate
data: function() {
return {
'text': this.value
}
},
components: {
VTextField
},
methods : {
onInput: function(value) {
this.$emit('input', value);
this.validation.$touch();
},
onBlur: function() {
this.validation.$touch();
}
},
watch: {
value: {
immediate: true,
handler: function (newValue) {
this.text = newValue
}
}
}
}
</script>
which is used in another component
<template>
...
<TextField v-model="personal.email" label="Email"
:validation="$v.personal.email" :errors="[]"/>
...
</template>
<script>
...imports etc.
export default { ...
data: function() {
return {
personal: {
email: '',
name: ''
}
}
},
components: [ TextField ]
}
</script>
This works fine but i wonder if there is a much more cleaner approach than to replicate the whole v-model approach again. As now my data is duplicated in 2 places + all the extra (non needed) event handling...
I just want to pass the reactive data directly through to the v-text-field from the original temlate. My TextField doesn't actually need access to that data at all - ONLY notified that the text has changed (done via the #input, #blur handlers). I do not wish to use VUEX as this has it's own problems dealing with input / forms...
Something more close to this...
<template>
<v-text-field
:label="label"
v-model="value" //?? SAME AS 'Mine'
#input="onNotify"
#blur="onNotify"
:error-messages="this.getErrors(this.validation, this.errors)"
></v-text-field>
</template>
<script>
import VTextField from "vuetify/es5/components/VTextField";
import {vuelidateErrorsMixin} from '~/plugins/common.js';
export default {
name: "TextField",
props: ['label', 'validation', 'errors'], //NO VALUE HERE as cannot use props...
mixins: [vuelidateErrorsMixin], //add vuelidate
components: {
VTextField
},
methods : {
onNotify: function() {
this.validation.$touch();
}
},
}
</script>
I cannot find anything that would do this.
Using props + v-model wrapping is what i do.
You need to forward the value prop down to the wrapped component, and forward the update event back up (see https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components for more details):
<template>
<wrapped-component
:value='value'
#input="update"
/>
</template>
<script>
import wrappedComponent from 'wrapped-component'
export default {
components: { 'wrapped-component': wrappedComponent },
props: ['value'],
methods: {
update(newValue) { this.$emit('input', newValue); }
}
}
</script>
Somewhere else:
<my-wrapping-component v-model='whatever'/>
I've create a mixin to simplify wrapping of a component.
You can see a sample here.
The mixin reuse the same pattern as you with "data" to pass the value and "watch" to update the value during a external change.
export default {
data: function() {
return {
dataValue: this.value
}
},
props: {
value: String
},
watch: {
value: {
immediate: true,
handler: function(newValue) {
this.dataValue = newValue
}
}
}
}
But on the wraping component, you can use "attrs" and "listeners" to passthrough all attributes and listener to your child component and override what you want.
<template>
<div>
<v-text-field
v-bind="$attrs"
solo
#blur="onBlur"
v-model="dataValue"
v-on="$listeners" />
</div>
</template>
<script>
import mixin from '../mixins/ComponentWrapper.js'
export default {
name: 'my-v-text-field',
mixins: [mixin],
methods: {
onBlur() {
console.log('onBlur')
}
}
}
</script>

How to share data between components Vue js

Hi there I saw posts talking about this, but is not easy for me understand what I have to do to share data between components, I don't want to use event bus so can you tell me how to use props??
Component A:
<template>
<div>
<div class="container">
<fileForm></fileForm> //<--- THE COMPONENT B
</div>
</div>
</div>
</template>
<script>
export default {
name: "DashBoard",
data() {
return {
user: {},
};
},
methods: {
checkIfImLoggedIn() {
}
},
onComplete() {
},
},
mounted() {
this.checkIfImLoggedIn();
}
};
</script>
Component B:
<template>
//...
</template>
<script>
export default {
name: "FileForm",
data() {
return {
fileExtensions: ["CSV", "EXCEL"],
sharedData : {}, //<--- for example share this
};
},
methods: {}
};
</script>
If you want to share data from the parent to the child you can do:
on component A
<fileForm :something="user"></fileForm>
In component B
props: {
something: Object
}
If you want to share data from the child to the parent you have to use an event bus or vuex: https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
https://alligator.io/vuejs/component-communication/
You need to do some research about communication among components.
There are a lot of ways to do it ;)