Passing different components with life cycle using vue - javascript

Having trouble with my life cycle method using vue. It seems that my coffeefinished variable isn't showing up. I don't know if I'm actually passing the right variables to make it show. Also when I click on the other buttons I get undefined for some strange reason, but only when i click mutliple times on the three buttons
const DrinkName = new Vue({});
const coffeeFinished = new Vue({});
Vue.component("customer-component",{
template: `
<div>
<button v-on:click="choose('drip brew')">Drip brew</button>
<button v-on:click="choose('frenchpress')">French Press</button>
<button v-on:click="choose('aeropress')">Aeropress</button>
</div>
`,
props: ['order_type'],
data: function () {
return{
order_type:"",
order_value: "",
drink: "",
showButtons: true,
orderAgain: false,
}
},
methods:{
choose(val) {
this.order_type = val;
if (val == "drip brew") {
this.order_value = "$5.10";
}
if (val == "frenchpress") {
this.order_value = "$8.75";
}
if (val == "aeropress") {
this.order_value = "$7.00";
}
DrinkName.$emit('customerOrdered', this.order_type, this.order_value)
}
}
}); // end of customer-component
Vue.component("barista-component",{
props: ['order_type','order_value'],
template:`
<div>
<transition name="fade">
<div order_type="order_type" order_value="order_value" v-if="order_type">
One {{order_type}}, that will be {{order_value}}.
</div>
</transition name="fade">
<transition>
<div v-if="drink">{{ drink }}</div>
</transition>
</div>
`,
data:function() {
return {
order_type: "",
order_value: "",
drink: "",
message:""
}
},
// Start of lifecycles
created() {
DrinkName.$on('customerOrdered', (myDrink,myPrice) => {
this.order_type = myDrink;
this.order_value = myPrice;
});
},
beforeUpdate: function () {
this.brewingDrink(this.order_type);
},
updated: function() {
this.drink = "";
},
methods: {
brewingDrink(val) {
setTimeout(() => {
this.drink = 'waiting for ' + val;
}, 1000);
coffeeFinished.$on('brewingcomplete', (mymessage,myDrink) =>{
this.order_type = myDrink;
this.message = 'here is your ' + this.order_value + ' , enjoy'
})
}
},
}); // end of barista-component
// start of the machine component
Vue.component("machine-component", {
props: ['order_type', 'order_value'],
template: `
<div>
<transition name="fade2">
<div order_type="order_type" v-if="order_type">
{{message}}
</transition name="fade">
</div>
</div>
`,
data: function () {
return {
order_type: "",
order_value: "",
drink: "",
message: ""
}
},
created: function () {
DrinkName.$on('customerOrdered', (myDrink) => {
this.order_type = myDrink;
this.message = 'Currently brewing ' + this.order_type;
this.brewingComplete(this.order_type);
});
},
methods: {
brewingComplete(val) {
setTimeout(() => {
this.message = val + ' is done';
}, 2500); // 10 seconds
coffeeFinished.$emit('brewingcomplete', false)
},
}
}); // end of machine-component
new Vue ({
el:"#app",
data:function () {
return {
showing: true
}
},
});
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cafe</title>
<link rel="stylesheet"href="style.css">
</head>
<body>
<!--user facing component -->
<div id="app">
<h1>How may I help you today </h1>
<div id="customer">
<customer-component>
</customer-component>
</div>
<div id="barista">
<barista-component>
</barista-component>
</div>
<machine-component>
</machine-component>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
<script src="JS/app.js"></script>
</body>
</html>

I'm not sure about what you want to show.
But i make an code pen demo to try to solve your problem.
const DrinkName = new Vue({});
const coffeeFinished = new Vue({});
Vue.component("customer-component",{
template: `
<div>
<button v-on:click="choose('drip brew')">Drip brew</button>
<button v-on:click="choose('frenchpress')">French Press</button>
<button v-on:click="choose('aeropress')">Aeropress</button>
</div>
`,
props: ['order_type'],
data: function () {
return{
order_type:"",
order_value: "",
drink: "",
showButtons: true,
orderAgain: false,
}
},
methods:{
choose(val) {
this.order_type = val;
if (val == "drip brew") {
this.order_value = "$5.10";
}
if (val == "frenchpress") {
this.order_value = "$8.75";
}
if (val == "aeropress") {
this.order_value = "$7.00";
}
DrinkName.$emit('customerOrdered', this.order_type, this.order_value)
}
}
}); // end of customer-component
Vue.component("barista-component",{
props: ['order_type','order_value'],
template:`
<div>
<transition name="fade">
<div order_type="order_type" order_value="order_value" v-if="order_type">
One {{order_type}}, that will be {{order_value}}.
</div>
</transition name="fade">
<transition>
<div v-if="drink">{{ drink }}</div>
<div v-if="message">{{ message }}</div>
</transition>
</div>
`,
data:function() {
return {
order_type: "",
order_value: "",
drink: "",
message:""
}
},
// Start of lifecycles
created() {
DrinkName.$on('customerOrdered', (myDrink,myPrice) => {
this.order_type = myDrink;
this.order_value = myPrice;
});
},
beforeUpdate: function () {
this.brewingDrink(this.order_type);
},
updated: function() {
this.drink = "";
},
methods: {
brewingDrink(val) {
setTimeout(() => {
this.drink = 'waiting for ' + val;
}, 1000);
coffeeFinished.$on('brewingcomplete', (mymessage,myDrink) =>{
this.order_type = myDrink;
this.message = 'here is your ' + this.order_value + ' , enjoy'
})
}
},
}); // end of barista-component
// start of the machine component
Vue.component("machine-component", {
props: ['order_type', 'order_value'],
template: `
<div>
<transition name="fade2">
<div order_type="order_type" v-if="order_type">
{{message}}
</transition name="fade">
</div>
</div>
`,
data: function () {
return {
order_type: "",
order_value: "",
drink: "",
message: ""
}
},
created: function () {
DrinkName.$on('customerOrdered', (myDrink) => {
this.order_type = myDrink;
this.message = 'Currently brewing ' + this.order_type;
this.brewingComplete(this.order_type);
});
},
methods: {
brewingComplete(val) {
setTimeout(() => {
this.message = val + ' is done';
coffeeFinished.$emit('brewingcomplete', false)
}, 10000); // 10 seconds
},
}
}); // end of machine-component
new Vue ({
el:"#app",
data:function () {
return {
showing: true
}
},
});
Your can check it out.hope can help :)

Related

vuejs onblur directive not working as expected, while should hide the list

I'm trying to make a simple dropdown search select list.
I'd like to hide the name list by clicking outside of it. And the issue is that when I click outside the list of search items by using #blur directive the appropriate list item doesn't fill the input field. It's assumingly because of the #click="selectCategory(category)" is triggered later than #blur="isVisible = false" in the template.
<template>
<div сlass="search-bar" :style="{'position' : (isVisible) ? 'absolute' : 'fixed'}">
<input
type="text"
v-model="input"
#focus="isVisible = true"
// #blur="isVisible = false" doesn't work as required
/>
<div class="search-bar-options" v-if="isVisible">
<div v-for="category in filteredUser" :key="category.id" #click="selectCategory(category)">
<p>{{ category.name }}</p>
</div>
<div v-if="filteredUser.length === 0">
<p>No results found!</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
input: "",
selectedItem: null,
categoriesDynamic: [],
isVisible: false,
};
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((json) => {
this.categoriesDynamic = json;
});
},
filteredUser() {
const query = this.input.toLowerCase();
if (this.input === "") {
return this.categoriesDynamic;
} else {
return this.categoriesDynamic.filter(category => {
return category.name.toLowerCase().includes(query);
});
}
},
},
methods: {
selectCategory(category) {
this.input = category.name;
this.isVisible = false;
},
},
};
</script>
<style scoped>
.pointer {
cursor: pointer;
}
.show {
visibility: show;
}
.hide {
visibility: hidden;
}
</style>
One solution could be to detect the clicked element. If the clicked element is not an input or a category element, then the dropdown can be closed.
Here is a working demo in which I gave a class "category" to each list item for element detecting purposes.
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data() {
return {
input: "",
selectedItem: null,
categoriesDynamic: [],
isVisible: false,
};
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((json) => {
this.categoriesDynamic = json;
});
},
created() {
document.addEventListener('click', (e) => {
let isInput = e.target instanceof HTMLInputElement;
let isCategoryEl = e.target.classList.contains('category');
if (isInput || isCategoryEl) return;
this.isVisible = false;
})
},
computed: {
filteredUser() {
const query = this.input.toLowerCase();
if (this.input === "") {
return this.categoriesDynamic;
} else {
return this.categoriesDynamic.filter(category => {
return category.name.toLowerCase().includes(query);
});
}
},
},
methods: {
selectCategory(category) {
this.input = category.name;
this.isVisible = false;
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div сlass="search-bar" :style="{'position' : (isVisible) ? 'absolute' : 'fixed'}">
<input
type="text"
v-model="input"
#focus="isVisible = true"
/>
<div class="search-bar-options" v-if="isVisible">
<div v-for="category in filteredUser" :key="category.id" #click="selectCategory(category)">
<p class="category">{{ category.name }}</p>
</div>
<div v-if="filteredUser.length === 0">
<p>No results found!</p>
</div>
</div>
</div>
</div>

Vue.js rendering after 2nd onClick

I have a form that uses dropdowns to allow the user to select their configuration and when they click apply a highchart is rendered. At first glance this works perfectly.
My problem is that if after the chart is rendered you open a dropdown again to make a change without closing the dropdown and click apply we get the chart with the previous configuration. I have to click apply a second time to get the new configuration to show up.
What am I missing?
Here is part of the complete code:
<template>
<div class="dropdown multiple-select">
<GlobalEvents v-if="open" #click="handleClick" #keydown.esc="close" />
<button
ref="button"
class="btn btn-block btn-multiple-select"
type="button"
:disabled="disabled"
#click="toggle"
>
<span v-if="internalValue.length === 0"> {{ emptyLabel }} </span>
<span v-else> {{ internalValue.length }} Selected </span>
<b-icon :icon="open | icon" :scale="0.5" />
</button>
<div ref="dropdown" class="dropdown-menu" :class="{ show: open }">
<template v-if="!loading">
<div class="px-4 pt-1">
<div class="form-group">
<b-form-input
v-model="search"
debounce="500"
placeholder="Search"
/>
</div>
</div>
<div class="scroll px-4">
<b-form-checkbox v-model="selectAll" class="py-1" #change="toggleAll">
Select all
</b-form-checkbox>
<b-form-checkbox
v-for="item in filtered"
:key="item.id"
v-model="internalValue"
:value="item"
class="py-1"
#input="checkSelectAllStatus"
>
{{ item.name }}
</b-form-checkbox>
<p v-if="filtered.length === 0">No results.</p>
</div>
</template>
<div v-else class="text-center my-2">
<b-spinner />
</div>
</div>
</div>
</template>
<script>
import { createPopper } from '#popperjs/core';
import GlobalEvents from 'vue-global-events';
export default {
components: {
GlobalEvents
},
filters: {
icon(item) {
return item ? 'caret-up-fill' : 'caret-down-fill';
}
},
model: {
prop: 'value',
event: 'change'
},
props: {
emptyLabel: {
type: String,
default: () => 'None Selected'
},
disabled: {
type: Boolean,
default: () => false
},
loading: {
type: Boolean,
default: () => false
},
options: {
type: Array,
default: () => []
},
value: {
type: Array,
default: () => []
}
},
data() {
return {
internalValue: this.value,
open: false,
popper: null,
search: '',
selectAll: false
};
},
computed: {
filtered() {
return this.options.filter((item) =>
item.name.toLowerCase().includes(this.search.toLowerCase())
);
},
showAll() {
return (
this.internalValue.length > 0 &&
this.internalValue.length === this.options.length
);
}
},
watch: {
options() {
this.checkSelectAllStatus();
},
internalValue() {
this.checkSelectAllStatus();
},
value(value) {
this.internalValue = value;
this.$emit('change', this.internalValue);
}
},
methods: {
checkSelectAllStatus() {
this.selectAll = this.internalValue.length === this.options.length;
},
close() {
this.open = false;
this.search = '';
this.$emit('change', this.internalValue);
},
create() {
this.popper = createPopper(this.$refs.button, this.$refs.dropdown, {
placement: 'bottom-start',
modifiers: [
{
name: 'offset',
options: {
offset: [0, 10]
}
}
]
});
},
destroy() {
if (this.popper) {
this.popper.destroy();
this.popper = null;
}
},
handleClick(event) {
if (!this.$el.contains(event.target)) {
this.close();
}
},
toggle() {
this.open = !this.open;
if (this.open) {
this.$emit('open');
this.create();
} else {
this.destroy();
}
},
toggleAll(checked) {
if (checked) {
this.internalValue = this.options;
} else {
this.internalValue = [];
}
}
}
};
</script>
Found a solution that works with what we already have. My MultipleSelect component was invoking #input="checkSelectAllStatus"
I added this.$emit('change', this.internalValue); to the checkSelectAllStatus method and it worked.
You seem to be using vuelidate - is there a good reason why you aren't accessing your form values directly but are going through your validation model instead?
Without knowing your config, your code should look more like this:
async apply() {
try {
this.chartOptions.utilityMetric = this.form.metric;
this.chartOptions.title = this.getTitle();
this.loading = true;
this.$v.$touch()
if (this.$v.$error) throw new Error('form not valid')
const response = await await this.$api.organizations.getAnnualWidget(
this.organizationId,
this.parentUtility,
this.requestParams
);
this.chartOptions.categories = response.data.categories;
this.chartOptions.series = response.data.series;
this.chartOptions.yAxis = response.data.yAxis;
this.$forceUpdate();
} catch (error) {
const message = getErrorMessage(error);
this.$bvToast.toast(message, {
title: 'Error',
toaster: 'b-toaster-top-center',
variant: 'danger'
});
} finally {
this.loading = false;
}
}
and
requestParams() {
return {
calendarization: this.form.calendarization,
metrics: this.form.metric.map((metric) => metric.id),
meterIds: this.form.meterIds,
Years: this.form.fiscalYears.map((year) => year.value),
waterType: this.form.waterType,
includeBaseline: this.form.baseLine,
showDataLabels: this.form.showDataLabels
};
},
Again, without knowing your complete code it's difficult to tell, but I am guessing it's the pointing to vuelidate that's causing the issues

Vue is not rendering v-for input fields from array after mutating the array

Vue component won't re-render array items after its value was set externally. State chenges but v-for element is not showing the changes.
I have a component that renders items from array. I also have buttons to change the array length and it works well: '+' adds one line and '-' removes the last line. The problem starts when I set the array data from a fetch method. Data is displayed but '+' and '-' buttons don't work.
Here's a link to codesanbox https://codesandbox.io/s/q9jv524kvw
/App.vue
<template>
<div id="app">
<button #click="downloadTemplate">Load data</button>
<HelloWorld :formData="formData" />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld
},
data() {
return {
fakeData: {
unloadingContactPersons: [
{
id: this.idGen("unloadingContactPersons"),
value: "123"
},
{
id: this.idGen("unloadingContactPersons"),
value: "1234"
},
{
id: this.idGen("unloadingContactPersons"),
value: "12345"
}
]
},
lengthDependentLoadings: [
"loadingDates",
"loadingAddresses",
"loadingContactPersons"
],
lengthDependentUnloadings: [
"unloadingDates",
"unloadingAddresses",
"unloadingContactPersons"
],
formData: {
unloadingContactPersons: [
{
id: this.idGen("unloadingContactPersons"),
value: ""
}
]
}
};
},
methods: {
idGen(string = "") {
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
return (
string +
"_" +
Math.random()
.toString(36)
.substr(2, 9)
);
},
addLine(id) {
console.log("id", id);
const parentName = id.split("_")[0];
const dependentArray = this.lengthDependentLoadings.includes(parentName)
? this.lengthDependentLoadings
: this.lengthDependentUnloadings;
dependentArray.forEach(objName => {
this.formData[objName]
? this.formData[objName].push({
id: this.idGen(objName),
value: ""
})
: null;
});
console.log("--length", this.formData.unloadingContactPersons.length);
},
removeLine(id) {
const parentName = id.split("_")[0];
const dependentArray = this.lengthDependentLoadings.includes(parentName)
? this.lengthDependentLoadings
: this.lengthDependentUnloadings;
dependentArray.forEach(objName => {
this.formData[objName] ? this.formData[objName].pop() : null;
});
console.log("--length", this.formData.unloadingContactPersons.length);
},
downloadTemplate(link) {
// fake fetch request
const getFunctionDummy = data =>
new Promise(resolve => setTimeout(resolve.bind(null, data), 1500));
// data setter
getFunctionDummy(this.fakeData).then(result => {
// set our data according to the template data
const templateKeys = Object.keys(result);
const templateData = result;
this.formData = {};
templateKeys.forEach((key, index) => {
let value = templateData[key];
console.log(value);
if (Array.isArray(value)) {
console.log("array", value);
this.formData[key] = value.map((item, id) => {
console.log("---from-template", item);
return {
id: this.idGen(key),
value: item.value
};
});
} else {
this.formData[key] = {
id: this.idGen(key),
value
};
}
});
});
}
},
mounted() {
// takes id number of item to be added
this.$root.$on("addLine", ({ value }) => {
console.log("---from-mounted", value);
this.addLine(value);
});
// takes id number of item to be removed
this.$root.$on("removeLine", ({ value }) => {
this.removeLine(value);
});
},
beforeDestroy() {
this.$root.$off("addLine");
this.$root.$off("removeLine");
}
};
</script>
/HelloWorld.vue
<template>
<div class="hello">
<div class="form-item">
<div class="form-item__label">
<label :for="formData.unloadingContactPersons"
>Contact person on unload:</label
>
</div>
<div class="form-item__input multiline__wrapper">
<div
class="multiline__container"
#mouseover="handleMouseOver(unloadingContactPerson.id);"
v-for="unloadingContactPerson in formData.unloadingContactPersons"
:key="unloadingContactPerson.id"
>
<span
class="hover-button hover-button__remove"
#click="removeLine(unloadingContactPerson.id);"
><i class="fas fa-minus-circle fa-lg"></i>-</span
>
<input
class="multiline__input"
:id="unloadingContactPerson.id"
type="text"
v-model="unloadingContactPerson.value"
#input="emitFormData"
/>
<span
class="hover-button hover-button__add"
#click="addLine(unloadingContactPerson.id);"
><i class="fas fa-plus-circle fa-lg"></i>+</span
>
</div>
</div>
</div>
</div>
</template>
<script>
import Datepicker from "vuejs-datepicker";
import { uk } from "vuejs-datepicker/dist/locale";
export default {
name: "SubmitForm",
components: {
Datepicker
},
props: {
formData: Object
},
data: () => {
return {
uk,
hoveredItemId: null
};
},
methods: {
emitFormData() {
this.$root.$emit("submitFormData", { value: this.formData });
},
handleMouseOver(id) {
this.hoveredItemId = id;
},
addLine(id) {
// console.log("---add", id);
this.$root.$emit("addLine", {
value: id
});
},
removeLine(id) {
// console.log("---remove", id);
this.$root.$emit("removeLine", {
value: id
});
}
}
};
</script>
Just comment line no 111 of App.vue and it will work.
// this.formData = {}
The problem is that you directly mutating formData object which Vue.js cannot detect. Read more about Array Change detection [List Rendering - Vue.js]

How do I call Axios on prop change in Vue?

On the change of the value id, I would like to make a JSON call via Axios and update necessary parts of the page. How do I do that? Currently, I have mounted and activated and they do not seem to be working...
Code:
const Home = {
template: `
<div class="user">
<h2>user {{ id }}</h2>
<h2>{{ info }}</h2>
bet
</div>
`,
props: {
id: {
type: String,
default: 'N/A'
}
},
data () {
return {
info: null
}
},
activated () {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json',
{ params: { id: id }}
)
.then(response => (this.info = response))
},
mounted() {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = 'response'))
}
}`
You can listen to id prop change by using watch:
watch: {
id: function(newId) {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json',
{ params: { id: newId }}
)
.then(response => (this.info = response))
}
}
Here is a little demo based on the code that you shared that shows how watch reacts to id prop change. Wrapper component below is solely for demonstration purpose as something that triggers id value change.
const Home = {
template: `
<div class="user">
<h2>user {{ id }}</h2>
<h2>{{ info }}</h2>
bet
</div>
`,
props: {
id: {
default: 'N/A'
}
},
data () {
return {
info: null
}
},
mounted() {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = 'response'))
},
watch: {
id: function(newId) {
console.log(`watch triggered, value of id is: ${newId}`);
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json',
{ params: { id: newId }}
)
.then(response => (this.info = response))
}
}
}
const Wrapper = {
template: '<div><home :id="id" /></div>',
components: { Home },
data() {
return {
id: 0
}
},
mounted() {
const limit = 5;
const loop = (nextId) => setTimeout(() => {
console.log(`#${nextId} loop iteration`);
if (nextId < limit) {
this.id = nextId;
loop(nextId + 1);
}
}, 3000);
loop(this.id);
}
}
new Vue({
el: '#app',
components: { Wrapper }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js" ></script>
<div id="app">
<wrapper />
</div>

Issue is update props with onchange(#change) in vue js 2

I am trying to update the data when doing on-change from the select box. Currently, i am able to the first time with the button click and also with on change. But I am not able to when doing the on-change multiple times.
<template>
<div>
<div class="row">
<select v-model="selectedemp" #change="filterempdata($event.target.value)">
<option value="">Select emp/option>
<option v-for="option in empfilterlist" v-bind:value="option.value" v-bind:key="option.value">{{ option.text }}</option>
</select>
</div>
<div class="row">
<empView v-if='loaded' :empDetails='empData'></empView>
</div>
<div class="col-lg-6 col-md-6">
<button type="button" id="btn2" class="btn btn-danger btn-md" v-on:click="getEmpDetails">Fetch Data</button>
</div>
</div>
</template>
Javascript part:
data () {
return {
loaded: false,
empData: {},
empfilterlist: [
{ text: 'Department', value: '1' },
{ text: 'Status', value: '2' },
],
selectedemp: '',
}
},
methods: {
filterempdata: function (selectedoption) {
console.log('Onchange value - ' + selectedOption)
Vue.set(this.empData, 'Department', selectedoption)
},
getEmpDetails: function () {
this.$http.get('http://localhost:7070/getemmdata')
.then((response) => {
this.empData = response.data
this.loaded = true
},
response => {
console.log('test' + JSON.stringify(response))
}
)
}
Child component javascript code:
export default {
name: 'empView',
props: ['empDetails'],
data () {
return {
empid: this.empDetails.id,
empname: this.empDetails.name
}
},
watch: {
empDetails: function (changes) {
console.log('data updated ' + JSON.stringify(changes))
this.empid = changes.id
this.empname = changes.name
this.department = changes.Department
}
}
}
Your code isn't complete. I've edited it and created a small example.
You call Vue.set(this.empData, 'Department', value);. Maybe there is a
spelling mistake, because I can't find this.empData.
UPDATE: Don't use camelCase for your html attributes (Use :empdetails instead of :empDetails). I've removed the on change attribute and replaced it with a computed values.
const empview = {
name: 'empview',
template: '<div>ID: {{empid}} TITLE: {{empname}} RANDNUM: {{random}}</div>',
props: ['empdetails'],
computed: {
empid() {
return this.empdetails.id;
},
empname() {
return this.empdetails.name;
},
random() {
return this.empdetails.random;
}
},
watch: {
workflowDetails(changes) {
console.log('data updated ' + JSON.stringify(changes))
this.empid = changes.id
this.empname = changes.name
this.department = changes.Department
}
}
};
new Vue({
el: '#app',
components: {
empview
},
data() {
return {
loaded: false,
empData: {},
empfilterlist: [
{
text: 'Department',
value: '1'
},
{
text: 'Status',
value: '2'
}
],
selectedemp: ''
}
},
watch: {
// triggers on change
selectedemp(value) {
// your filterempdata() code
console.log(value);
}
},
methods: {
/*getEmpDetails() {
this.$http.get('http://localhost:7070/getemmdata')
.then((response) => {
this.empData = response.data
this.loaded = true
}, (response) => {
console.log('test' + JSON.stringify(response))
})
}*/
getEmpDetails() {
console.log('getEmpDetails()');
const data = this.empfilterlist.filter((emp) => emp.value == this.selectedemp)[0];
if(data) {
this.empData = {
id: data.value,
name: data.text,
random: Math.random()
};
this.loaded = true;
}
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body class="container">
<div id="app">
<div>
<div class="row">
<select v-model="selectedemp">
<option value="">Select emp</option>
<option v-for="option in empfilterlist" :value="option.value" :key="option.value">{{option.text}}</option>
</select>
</div>
<div class="row">
<empview v-if='loaded' :empdetails='empData'></empview>
</div>
<div class="col-lg-6 col-md-6">
<button type="button" id="btn2" class="btn btn-danger btn-md" #click="getEmpDetails">Fetch Data</button>
</div>
</div>
</div>
<script src="https://vuejs.org/js/vue.js"></script>
</body>
</html>

Categories

Resources