How to get selected option from selected componets in Vue.js? - vue.js

<div class="fligtInput flex flex-no-wrap">
<SelectFlight
v-model="flight.model1" placeholder="from"
></SelectFlight>
<SelectFlight
v-model="flight.model2" placeholder="to"
></SelectFlight>
</div>
I use (select option) SelectFlight Component and this returns a JSON object. I wanna take the selected options for both components in parent component.

I will take a stab at an example showing multiple options, knowing I don't have the full context of your specific problem, but I am sure this example will get you pointed in the right direction.
I took liberty with object names, and assumed values in JSON objects. Obviously you will ned to adjust this for your specific use case and data.
<template>
<div class="i-am-the-parent">
<!--
Display flight from name
-->
<div
v-if="flights.from"
class="display-text-from"
>
{{ flights.from.airportName }}
</div>
<SelectFlight
v-model="flights.from"
placeholder="from"
/>
<!-- Bind flight to "airportName" as a prop in parent -->
<ParentWrapperComponent
class="display-text-to"
:airport-name="flights.to ? flights.to.airportName : null"
>
<!--
Nested in ParentWrapperComponent
-->
<SelectFlight
v-model="flights.to"
placeholder="to"
/>
</ParentWrapperComponent>
<!--
Kitchen Sink
Here I am demonstrating multiple approaches:
1. Merge the data via a computed property and pass as a property named airports
2. Simply pass the flights data property as a flights property
3. Simply pass the properties "flights.from" data as property "from" and "flights.to" data as property "to"
-->
<SomeComponentToShowBoth
:airports="combineValues"
:flights="flights"
:from="flights.from"
:to="flights.to"
/>
</div>
</template>
<script>
import SelectFlight from '#/path/to/component/SelectFlight'
export default {
components: {
SelectFlight
},
data () {
return {
flights: {
from: null,
to: null
}
}
},
computed: {
combineValues () {
// this will return both json objects merged into one.
// It will update everytime this.flights.from or this.flights.to changes
return Object.assign({}, this.flights.from, this.flights.to)
},
combineFlightNames () {
// Perhaps you just want to pass the names?
return {
from: flights.from ? flights.from.airportName : null,
to: flights.to ? flights.to.airportName : null
}
}
}
}
</script>
References:
Vue Computed Properties
Vue Component Props
Vue Reactivity

Related

how can i access data property in html template using loop in vue js

i'm trying to use data property commentsToShow in my html template to limit the amount of data that displays on my webpage
this is my template
<div v-if="index < products.length" v-for="(commentIndex, index) in computedProduct">
<div class="title pt-4 pb-1">{{products[index].title}}</div>
</div>
if i add commentsToShow in my for loop i get one product but the computed products doesn't work same way the other way round
this my script tag
<script>
export default {
data() {
return {
commentsToShow: 1,
totalComments: 0,
};
},
computed: {
computedProduct() {
let tempRecipes = this.products;
if (this.filterPrice !== "true");
}
};
</script>
if i change computed property to commentsToShow this the error i get in my console
The computed property "commentsToShow" is already defined in data.
please how can i get the value of commentToShow in my template
according to vue's official docs it's not recommended to use v-for and v-if on the same element
try using v-if on a wrapper div or template element
<div v-for="(commentIndex, index) in computedProduct">
<template v-if="index < products.length">
<div class="title pt-4 pb-1">{{products[index].title}}</div>
</template>
</div>
v-if has higher priority so it's executed first and index will not be defined yet.
also you have to return something on your computed property function in order to use it
You can use the slice method on a computed property, like this:
<script>
export default {
data() {
return {
commentsToShow: 1,
allComments: []
};
},
computed: {
listComments() {
return allComments.slice(0, commentsToShow);
}
};
</script>
You can also use pages to show the comments, in this case you can return like this:
return allComments.slice((currentPage - 1) * commentToShow, commentsToShow);
The first argument of slice is the start index, the second is the number of elements to get
The computed property "commentsToShow" is already defined in data.
Equivalently how you cannot have more than one variable with the same name defined in a scope. A computed property cannot have the same name as an existing data property. Essentially, they co-exist in the same namespace, thus they have to be unique.
You have a name clash, and that is what the error is saying.

vue v-for: translate with switch in vue i18n

I have a problem to translate the information with vue i18n that is called through "v-for", all the data from the template is translated without problem, but those that I export through arrays and scripts do not render
i am using vue-i18n: version 7.8.1
You're only ever setting the helpTitles property when your component is created.
I would suggest using $t() in your templates instead of within data(). Then it will automatically react to changes.
I honestly don't think using an array from the translation file is a great idea. I'd be more inclined to add them with their own keys, just like your question and info translation keys, eg
helpStartedTitle: "GETTING STARTED - MODEL",
helpMembersTitle: "MEMBERS",
helpAccountTitle: "ACCOUNT",
//etc
You could then set up the keys in your data like this
data: () => {
const keys = [
"helpStarted",
"helpMembers",
"helpAccount",
"helpPayment",
"helpSocial",
"helpFraud",
"helpSupport",
"helpStudio"
]
return {
helpInfo: keys.map((key, id) => ({
id,
title: `general.help.${key}Title`,
question: `general.help.${key}`,
answer: `general.help.${key}Info`
}))
}
}
then in your template
<div v-for="help in helpInfo" :key="help.id">
<div :id="help.id" class="help-subtitle">{{ $t(help.title) }}:</div>
<HelpItem
:question="$t(help.question)"
:answer="$t(help.answer)"
:num="help.id"
/>
</div>
Even better would be to just pass the translation keys through to your HelpItem component and use $t() with it.
<HelpItem
:question="help.question"
:answer="help.answer"
:num="help.id"
/>
and in the HelpItem component
export default {
name: "HelpItem",
props: {
question: String,
answer: String,
num: Number
},
// etc
}
<!-- just guessing here -->
<h1>{{ $t(question) }}</h1>
<p>{{ $t(answer) }}</p>
FYI, I've corrected answear to answer throughout.

v-model not always updating in Vue

Short question
The v-model which binds a string to an input field won't update in some cases.
Example
I am using Vue within a Laravel application. This is the main component which contains two other components:
<template>
<div>
<select-component
:items="items"
#selectedItem="updateSelectedItems"
/>
<basket-component
:selectedItems="selectedItems"
#clickedConfirm="confirm"
#clickedStopAll="stopAll"
/>
<form ref="chosenItemsForm" method="post">
<!-- Slot for CSRF token-->
<slot name="csrf-token"></slot>
<input type="text" name="chosenItems" v-model="selectedItemsPipedList" />
</form>
</div>
</template>
<script>
export default {
props: ["items"],
data: function() {
return {
selectedItems: [],
selectedItemsPipedList: ""
};
},
methods: {
updateSelectedItems: function(data) {
this.selectedItems = data;
this.selectedItemsPipedList = this.selectedItems
.map(item => item.id)
.join("|");
},
confirm() {
this.$refs.chosenItemsForm.submit();
},
stopAll() {
this.updateSelectedItems([]);
this.confirm();
}
}
};
</script>
The method updateSelectedItems is called from the select-component and it works fine. In the end, the selectedItemsPipedList contains the selected items from the select-component, which looks like "1|2|3" and this value is bound to the input field in the chosenItemsForm. When the method confirm is called from the basket-component, this form is posted to the Laravel backend and the post request contains the chosen items as piped list. So far, so good.
The method stopAll is called from the basket-component and it will remove all the selected items from the array. Therefore it will call the method updateSelectedItems with an empty array, which will clear the selectedItems array and then clear the selectedItemsPipedList. After that, confirm is called which will post the form again. But, the post value still contains the selected items (e.g. '1|2|3'), instead of "". It looks like the v-model in my form is not updated, which is strange because it does work when selecting items. Why is it working when adding items, and doesn't when removing all items?
I believe you have a timing issue here. The value of the properties haven't been propagated to the DOM yet, so the form submission is incorrect. Try this instead:
stopAll() {
this.updateSelectedItems([]);
//NextTick waits until after the next round of UI updates to execute the callback.
this.$nextTick(function() {this.confirm()});
}

[Vue warn]: Property or method "Boston" is not defined on the instance but referenced during render

I'm setting up some props, as shown below.
Component 1 (Parent):
<template>
<div>
<span>{{agency1}}</span>
<span>{{workstation}}</span>
</div>
</template>
<script>
export default {
name: "work-station-view",
props: {
agency1: {
type: String
},
workstation: {
type: Number
}
},
data() {
return {};
}
};
</script>
Component 2 (Child):
<template>
<WorkStationView :workstation="1.1" :agency1="Boston" />
</template>
The workstation prop renders fine, but the agency1 prop doesn't show up at all. I get this message from Vue in the console:
[Vue warn]: Property or method "Boston" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
I checked the docs, as it says to define it in data(), so I did a combination of all of these (probably more) to no avail:
// attempt 1
data() {
agency1 = this.agency1;
return {};
}
// attempt 2
data() {
return {
agency1 = this.agency1;
};
}
// attempt 3
data() {
return {
agency1: '';
};
}
If I use a number value for agency1 (<WorkStationView :workstation="1.1" :agency1="3" />), it shows! What is going on?
If you're using an inline string, you should skip the : or quote your string.
The : is short-hand for v-bind and is expected to be used with variables that you're binding when passing attributes from the parent component to the child. In this case, you don't have a variable called Boston in the parent context, and hence the error from Vue.
If all you want to do is use a constant string like Boston, just use it like
<WorkstationView :workstation="1.1" :agency="'Boston'" />
Alternatively, it would've also worked if you did the following:
<WorkstationView :workstation="1.1" agency="Boston" />
:agency1="Boston" is shorthand for v-bind:agency1="Boston". It attempts to bind a data property named Boston, but you don't have one defined. :agency1="3" works because 3 is a literal. If you were attempting to assign the literal string "Boston" to agency1, don't use the preceding colon:
<!--
<WorkStationView :agency1="Boston">
--> <!-- DON'T DO THIS -->
<WorkStationView agency1="Boston">

Binding method result to v-model with Vue.js

How do you bind a method result to a v-model with Vue.js?
example :
<someTag v-model="method_name(data_attribute)"></someTag>
I can't make it work for some reason.
Thank you.
Years later, with more experience, I found out that is it easier to bind :value instead of using v-model. Then you can handle the update by catching #change.
Edit (per request):
<input :value="myValue" #change="updateMyValue">
...
methods: {
updateMyValue (event) {
myValue = event.target.value.trim() // Formatting example
}
}
And in a child component:
// ChildComponent.vue
<template>
<button
v-for="i in [1,2,3]">
#click="$emit('change', i) />
</template>
// ParentComponent.vue
<template>
<child-component #change="updateMyValue" />
</template>
<script>
import ChildComponent from './child-component'
export default {
components: {
ChildComponent
},
data () {
return {
myvalue: 0
}
},
methods: {
updateMyValue (newValue) {
this.myvalue = newValue
}
}
}
</script>
v-model expressions must have a get and set function. For most variables this is pretty straight forward but you can also use a computed property to define them yourself like so:
data:function(){
return { value: 5 }
},
computed: {
doubleValue: {
get(){
//this function will determine what is displayed in the input
return this.value*2;
},
set(newVal){
//this function will run whenever the input changes
this.value = newVal/2;
}
}
}
Then you can use <input v-model="doubleValue"></input>
if you just want the tag to display a method result, use <tag>{{method_name(data_attribute)}}</tag>
Agree with the :value and #change combination greenymaster.
Even when we split the computed property in get/set, which is help, it seems very complicated to make it work if you require a parameter when you call for get().
My example is a medium sized dynamic object list, that populates a complex list of inputs, so:
I can't put a watch easily on a child element, unless I watch the entire parent list with deep, but it would require more complex function to determine which of the innter props and/or lists changed and do what fromthere
I can't use directly a method with v-model, since, it works for providing a 'get(param)' method (so to speak), but it does not have a 'set()' one
And the splitting of a computed property, have the same problem but inverse, having a 'set()' but not a 'get(param)'