Need To Access an Array of Objects with Vue.js - javascript

When the user selects a machine, I get the id of the machine. From that id I need to get the make and model of the machine.
<ul class="list-unstyled">
<li>
<div v-for="dosimeter in dosimeters">
<label>
<input type="radio" name="optDosimeter" v-model="dosimeter_id" :value="dosimeter.id" v-on:click="dosimeter_select">{{dosimeter.nickname}}
</label>
</div>
</li>
</ul>
Vue.js
export default {
data: function() {
return {
dosimeters:[],
dosimeter_id:''
}
},
mounted(){
axios.get('/dosimeters').then((response) => {
this.dosimeters=response.data;
});
},
methods: {
dosimeter_select(){
not sure what to put here
}
}
}

i think you should do something like :
dosimeter_select(){
let found= this.dosimeters.find(d=>{
return d.id==this.dosimeter_id
});
console.log(found.make);
console.log(found.model);
}

try this
dosimeter_select()
{
let machine = this.dosimeters.find(dosimeter => dosimeters.id===this.dosimeter_id);
// now you have the machine object
}

it should work:
new Vue({
el: "#app",
data: {
dosimeters:[
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' }
]
},
methods: {
dosimeterSelected (selectedDosimeter) {
console.log(`i doing something with dosimeter.id: ${selectedDosimeter.id}`)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul class="list-unstyled">
<li v-for="dosimeter in dosimeters">
<div>
<label>
<input type="radio" name="optDosimeter" :value="dosimeter.name" v-on:click="dosimeterSelected(dosimeter)">{{dosimeter.name}}
</label>
</div>
</li>
</ul>
</div>

I made some changes now it works.
I used the suggestion from Boussadjra Brahim:
dosimeter_select(){
let found= this.dosimeters.find(d=>{
return d.id==this.dosimeter_id
});
console.log(found.make);
console.log(found.model);
}
and rather than using radio buttons I made it a select drop down. Also, rather than triggering the method with #click, I used #change.

Related

vuejs remove key and value from URL based on conditions

I am making a simple filter and In this filter I am pushing query parameters to URL and appending them. If user choose a particular option, I want to modify the query string and I need the help here.
My URL is like this : http://app.test/home?preference=onsite&place=Aus&place=Mus
and if user choose wfh instead of onsite for preference I want to remove place from URL and want this URL: http://app.test/home?preference=wfh
my code:
<template>
<div>
<div class="mt-2">
</div>
<div class="mt-2" v-if=" this.$route.query.preference == 'onsite'">
<label>Available for work</label>
<div class="form-control" >
<input type="text">
<div class="options" style="max-height:140px;overflow:scroll">
<ul class="" style="max-height:40px;">
<li v-for="place in places" :key="place.id">
<input type="checkbox" v-model="filter.place"
:value="place.name">{{ place.name }}
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
places: [
{
id: 1,
name: "Aus",
},
{
id: 2,
name: "Mus",
},
],
filter: {
preference: this.$route.query.preference,
place:[],
},
};
},
watch: {
filter: {
handler() {
const query = this.filter
this.$router.push({
query: query,
});
},
deep: true,
},
},
};
</script>
I wrote below code to check if preference is wfh and update URL but this is not working
if (this.$route.query.preference == 'wfh') {
this.$route.query.place='';
this.$router.replace({ query: query });
}
You can extract the rest of the queries and replace with them, it same like delete place query.
if (this.$route.query.preference == 'wfh') {
const { place, ...query} = this.$route.query;
this.$router.replace({ query: query });
}

Vue.js update contents in div dynamically

I am attempting to do a SPA using Vue.js but unfortunately I know almost nothing about it, I followed a tutorial and got something up and running. This should hopefully be relatively simple!
I'm trying to create a simple page that:
Does a REST API call and pulls some JSON
A list with links of a particular field in the list of results is displayed on the left side of the screen
(I've managed until here)
Now I would like to be able to click on one of the links and see on the right side of the screen the value of another field for the same record.
For instance, suppose my JSON is:
{
"jokes":{
[
"setup":"setup1",
"punchline":"punchline1"
],
[
"setup":"setup2",
"punchline":"punchline2"
],
[
"setup":"setup3",
"punchline":"punchline3"
]
}
}
So in my screen I would see:
setup1
setup2
setup3
So if I click in setup1 I see punchline1, setup2 displays punchline2 and so on.
Here is my code - I'm basically trying to display the punchline in the moduleinfo div. I realise the current solution does not work. I've been searching but can't find any similar examples. Any pointers would be greatly appreciated.
<template>
<div class="home">
<div class="module-list">
<input type="text" v-model.trim="search" placeholder="Search"/>
<div>
<ul>
<li class="modules" v-for="value in modulesList" :key="value.id">
{{ value.setup }}
</li>
</ul>
</div>
</div>
<div class="moduleinfo">
<h2>Module info</h2>
<!-- <p>{{ value.punchline }}</p> -->
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Home',
data: function(){
return {
jokes: [],
search : ""
}
},
mounted() {
this.getModules();
},
methods: {
getModules() {
var self = this
const options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/joke/search',
params: {term: 'car'},
headers: {
'x-rapidapi-key': '...',
'x-rapidapi-host': 'dad-jokes.p.rapidapi.com'
}
};
axios.request(options)
.then(response => {
self.jokes = response.data;
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
}
},
computed: {
modulesList: function () {
var jokes = this.jokes.body;
var search = this.search;
if (search){
jokes = jokes.filter(function(value){
if(value.setup.toLowerCase().includes(search.toLowerCase())) {
return jokes;
}
})
}
return jokes;
}
},
};
</script>
Thanks!
I was building a sample Single File Component in my Vue 2 CLI app, and when I came back to post it, Ryoko had already answered the question with the same approach that I recommend, adding a new property to track showing the punchline.
Since I already built it, I figured that I might as well post my component, which does change the layout, using a table instead of a list, but the functionality works.
<template>
<div class="joke-list">
<div class="row">
<div class="col-md-6">
<table class="table table-bordered">
<thead>
<tr>
<th>SETUP</th>
<th>PUNCHLINE</th>
</tr>
</thead>
<tbody>
<tr v-for="(joke, index) in jokes" :key="index">
<td>
{{ joke.setup }}
</td>
<td>
<span v-if="joke.showPunchline">{{ joke.punchline }}</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
jokes: [
{
setup: "setup1",
punchline: "punchline1"
},
{
setup: "setup2",
punchline: "punchline2"
},
{
setup: "setup3",
punchline: "punchline3"
}
]
}
},
methods: {
getPunchline(index) {
this.jokes[index].showPunchline = true;
},
addPropertyToJokes() {
// New property must be reactive
this.jokes.forEach( joke => this.$set(joke, 'showPunchline', false) );
}
},
mounted() {
this.addPropertyToJokes();
}
}
</script>
You can add a new property inside the data object and then make a new method to set it accordingly when you click the <a> tag. Have a look at the code below, it was a copy of your current solution, edited & simplified to show the addition that I made to make it easier for you to find it.
The select method will insert the object of the clicked joke to the selectedJoke so you can render it below the Module Info.
Because it's defaults to null, and it might be null or undefined, you have to add v-if to the attribute to check wether there is a value or not so you don't get error on the console.
<template>
<div class="home">
<div class="module-list">
<input type="text" v-model.trim="search" placeholder="Search"/>
<div>
<ul>
<li class="modules" v-for="value in modulesList" :key="value.id">
{{ value.setup }}
</li>
</ul>
</div>
</div>
<div class="moduleinfo">
<h2>Module info</h2>
<p v-if="selectedJoke">{{ selectedJoke.punchline }}</p>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Home',
data: function(){
return {
jokes: [],
search : "",
selectedJoke: null,
}
},
methods: {
select(joke) {
this.selectedJoke = joke;
},
},
};
</script>

I've created multiple filters functions and each one does its own job right, however, I'm not sure how to chain them so they all work together

I'm trying to create filtering functionality which would allow me to filter cards from a collectible card game based on several criteria. I've already created 6 functions which filter based on a single criteria like card name, card cost or card rarity. These functions work fine and do their job, however, right now I can only use one of them at a time.
What I am trying to do is combine or chain these functions so that they are all taken into account before returning the final array with cards. I'm wondering if there's any easy way to do that?
Right now I have this:
<template>
<div class="cards">
<div class="cards-list">
<div class="card" v-for='card in filteredByCost' #click='specificCard(card.cardCode)'>
<div class="card-image">
<img class='responsive-image' :src='"../assets/cards/" + card.cardCode + ".png"' alt="">
</div>
</div>
</div>
</div>
</template>
<script>
import cards from '../assets/cards/set1-en_us.json'
import router from '../router'
export default {
data() {
return {
cards: cards,
search: '',
regions: ['Demacia', 'Noxus'],
cost: [7],
attack: [3, 5],
health: [4, 7],
rarity: ['Champion']
}
},
methods: {
specificCard(cardCode){
router.push({ name: 'specificCard', params: { cardCode: cardCode } })
}
},
computed: {
filteredByName(){
return this.cards.filter((card) => {
return card.name.match(this.search)
})
},
filteredByRegion(){
return this.cards.filter((card) => {
return this.regions.includes(card.region)
})
},
filteredByCost(){
return this.cards.filter((card) => {
return this.cost.includes(card.cost)
})
},
filteredByRarity(){
return this.cards.filter((card) => {
return this.rarity.includes(card.rarity)
})
},
filteredByAttack(){
return this.cards.filter((card) => {
return this.attack.includes(card.attack)
})
},
filteredByHealth(){
return this.cards.filter((card) => {
return this.health.includes(card.health)
})
},
}
}
</script>
Information
Place all your filter methods in the methods attribute on the vue instance
Create a way to enable/disable the filters
Create a computed property that looks at your #2 in this list and applies the proper filters accordingly
My rough example
new Vue({
el: "#app",
data () {
return {
filterEnabler: {
search: false,
sort: false
},
formInputs: {
searchText: ''
},
entries: [
'vue',
'react',
'angular',
'svelte'
]
}
},
computed: {
filteredEntries () {
let { entries, filterEnabler } = this
entries = entries.slice(0)
if (filterEnabler.search) entries = this.searchFilter(entries)
if (filterEnabler.sort) entries = this.sortFilter(entries)
return entries
}
},
methods: {
searchFilter (entries) {
return entries.filter(entry => entry.indexOf(this.formInputs.searchText) !== -1)
},
sortFilter (entries) {
return entries.sort()
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="filters">
<div class="search-filter">
<input type="checkbox" v-model="filterEnabler.search" /> Search Filter
<div v-if="filterEnabler.search">
<input placeholder="type here" type="text" v-model="formInputs.searchText" />
</div>
</div>
<div class="sort-filter">
<input type="checkbox" v-model="filterEnabler.sort" /> Sort Filter
</div>
</div>
<ul>
<li v-for="entry in filteredEntries" :key="entry">{{entry}}</li>
</ul>
</div>
In my example, you can see this I have 2 filters, search and sort - when one of their filterEnablers is toggeled true, it will apply all the enabled filters to the data and then return a new, separate array (very important, try not to mutate your source of truth, in my case, that's entries)
Hope this helps!

Click-and-edit text input with Vue

I'm looking for a click-and-edit Vue component.
I've found a fiddle and made some edits. It works like this:
The fiddle is here.
The problem: I need an additional click to make the input focused. How can I make it focused automatically?
The code from the fiddle. HTML:
<div id="app">
Click the values to edit!
<ul class="todo-list">
<li v-for = "todo in todos">
<input v-if = "todo.edit" v-model = "todo.title"
#blur= "todo.edit = false; $emit('update')"
#keyup.enter = "todo.edit=false; $emit('update')">
<div v-else>
<label #click = "todo.edit = true;"> {{todo.title}} </label>
</div>
</li>
</ul>
</div>
JS:
new Vue({
el: '#app',
data: {
todos: [{'title':'one value','edit':false},
{'title':'one value','edit':false},
{'title':'otro titulo','edit':false}],
editedTodo: null,
message: 'Hello Vue.js!'
},
methods: {
editTodo: function(todo) {
this.editedTodo = todo;
},
}
})
You can use a directive, for example
JS
new Vue({
el: '#app',
data: {
todos: [
{ title: 'one value', edit: false },
{ title: 'one value', edit: false },
{ title: 'otro titulo', edit: false }
],
editedTodo: null,
message: 'Hello Vue.js!'
},
methods: {
editTodo: function (todo) {
this.editedTodo = todo
}
},
directives: {
focus: {
inserted (el) {
el.focus()
}
}
}
})
HTML
<div id="app">
Click the values to edit!
<ul class="todo-list">
<li v-for="todo in todos">
<input
v-if="todo.edit"
v-model="todo.title"
#blur="todo.edit = false; $emit('update')"
#keyup.enter="todo.edit=false; $emit('update')"
v-focus
>
<div v-else>
<label #click="todo.edit = true;"> {{todo.title}} </label>
</div>
</li>
</ul>
</div>
You can find more info here
https://v2.vuejs.org/v2/guide/custom-directive.html
With #AitorDB's help I have written a Vue component for this, I call it Click-to-Edit. It is ready to use, so I'm posting it.
What it does:
Supports v-model
Saves changes on clicking elsewhere and on pressing Enter
ClickToEdit.vue: (vue 2.x)
<template>
<div>
<input type="text"
v-if="edit"
:value="valueLocal"
#blur.native="valueLocal = $event.target.value; edit = false; $emit('input', valueLocal);"
#keyup.enter.native="valueLocal = $event.target.value; edit = false; $emit('input', valueLocal);"
v-focus=""
/>
<p v-else="" #click="edit = true;">
{{valueLocal}}
</p>
</div>
</template>
<script>
export default {
props: ['value'],
data () {
return {
edit: false,
valueLocal: this.value
}
},
watch: {
value: function() {
this.valueLocal = this.value;
}
},
directives: {
focus: {
inserted (el) {
el.focus()
}
}
}
}
</script>
Edit for 3.x: [Breaking changes between 2.x and 3.x]
remove .native from the event handlers
change the focus hook to mounted as described in Custom Directives 3.x.
Built on #Masen Furer's work. I added some protection to handle when a user deletes all of the data. There is probably a way to accomplish this using "update" but I couldn't get it working.
I also added the ability to hit escape and abandon any changes.
<template>
<span>
<input type="text"
v-if="edit"
:value="valueLocal"
#blur="save($event);"
#keyup.enter="save($event);"
#keyup.esc="esc($event);"
v-focus=""/>
<span v-else #click="edit = true;">
{{valueLocal}}
</span>
</span>
</template>
<script>
export default {
props: ['value'],
data () {
return {
edit: false,
valueLocal: this.value,
oldValue: (' ' + this.value).slice(1)
}
},
methods: {
save(event){
if(event.target.value){
this.valueLocal = event.target.value;
this.edit = false;
this.$emit('input', this.valueLocal);
}
},
esc(event){
this.valueLocal = this.oldValue;
event.target.value = this.oldValue;
this.edit = false;
this.$emit('input', this.valueLocal);
}
},
watch: {
value: function() {
this.valueLocal = this.value;
}
},
directives: {
focus: {
inserted (el) {
el.focus()
}
}
}
}
</script>

Getting index of a data in an array in VUE js

I want to change the status of Tasks when a particular method is called. But The problem is I cannot get the index of the particular item of the array to change its status.
This is my HTML:
<div class="main" id="my-vue-app">
<ul>
<li v-for="task in completeTask">
{{ task.description }} <button #click="markIncomplete">Mark as Incomplete</button>
</li>
</ul>
<ul>
<li v-for="task in incompleteTask">
{{ task.description }} <button #click="markComplete">Mark as Complete</button>
</li>
</ul>
</div>
And this is my Vue:
<script>
new Vue(
{
el: '#my-vue-app',
data:
{
tasks: [
{description:'go to market', status: true},
{description:'buy book', status: true},
{description:'eat biriani', status: true},
{description:'walk half kilo', status: false},
{description:'eat icecream', status: false},
{description:'return to home', status: false}
]
},
computed:
{
incompleteTask()
{
return this.tasks.filter(task => ! task.status);
},
completeTask()
{
return this.tasks.filter(task => task.status);
}
},
methods:
{
markComplete()
{
return this.task.status = true;
},
markIncomplete()
{
return this.task.status = false;
}
}
}
)
</script>
I need make use of markComplete() and markIncomplete() but the problem is I couldn't find the way to get the index of current element to change its status.
You could get the index by declaring a second argument at the v-for:
<li v-for="(task, index) in incompleteTask">
{{ task.description }} <button #click="markComplete(index)">Mark as Complete</button>
</li>
methods:
{
markComplete(index)
{
return this.tasks[index].status = true;
},
But a, maybe simpler, alternative is to simply **pass the `task` as argument**:
<li v-for="task in incompleteTask">
{{ task.description }} <button #click="markComplete(task)">Mark as Complete</button>
</li>
methods:
{
markComplete(task)
{
return task.status = true;
},
RTFM:
You can use the v-repeat directive to repeat a template element
based on an Array of objects on the ViewModel. For every object in the
Array, the directive will create a child Vue instance using that
object as its $data object. These child instances inherit all data
on the parent, so in the repeated element you have access to
properties on both the repeated instance and the parent instance. In
addition, you get access to the $index property, which will be the
corresponding Array index of the rendered instance.
var demo = new Vue({
el: '#demo',
data: {
parentMsg: 'Hello',
items: [
{ childMsg: 'Foo' },
{ childMsg: 'Bar' }
]
}
})
<script src="https://unpkg.com/vue#0.12.16/dist/vue.min.js"></script>
<ul id="demo">
<li v-repeat="items" class="item-{{$index}}">
{{$index}} - {{parentMsg}} {{childMsg}}
</li>
</ul>
Source:
https://012.vuejs.org/guide/list.html
Note: The directive v-repeat is available in old versions of Vue.js :-)

Categories