Vue - passing data via Event.$emit - javascript

I have a question about passing data through Event.$emit. I have a parent that has a click event (appSelected) like this
<template>
<v-app>
<v-container>
<v-select :items="results" item-text="name" item-value="id" v-model="selectedOption" #change="appSelected"
:results="results"
label="Choose Application"
dense
></v-select>
</v-container>
</v-app>
</template>
In that component I have a method that emits the data. This is the id - this.selectedOption
appSelected() {
//alert("This is the id" + this.selectedOption);
Event.$emit('selected', this.selectedOption);
In my child component I would like to pass and use the value but can't seem to get it to work. I have a v-if on the top level div that if it sees a true it will show all below. That works great, but I need the id that's being passed.
This works for showing the div, but need to pass and use the id also. How can I pass the and use the id?
Event.$on('selected', (data) => this.appselected = true);
<template>
<div v-if="appselected">
Choose the Client Source
<input type="text" placeholder="Source client" v-model="query"
v-on:keyup="autoComplete"
v-on-clickaway="away"
#keydown.esc="clearText" class="form-control">
<span class="instructiontext"> Search for id, name or coid</span>
<div class="panel-footer" v-if="results.length">
<ul class="list-group">
<li class="list-group-item" v-for="result in results">
{{ result.name + "-" + result.oid }}
</li>
</ul>
</div>
</div>
</template>
<script>
import axios from 'axios'
import { directive as onClickaway } from 'vue-clickaway';
export default{
directives: {
onClickaway: onClickaway,
},
data(){
return {
add_id: '',
onSelecton: '',
input_disabled: false,
selected: '',
query: '',
results: [],
appselected: false
}
},
methods: {
getClient(name) {
this.query = name;
this.results = [];
},
clearText(){
this.query = '';
},
away: function() {
// Added for future use
},
autoComplete(){
this.results = [];
if(this.query.length > 2){
axios.get('/getclientdata',{params: {query: this.query}}).then(response => {
this.results = response.data;
});
}
}
},
created() {
Event.$on('selected', (data) => this.appselected = true);
console.log(this.appselected);
}
}
</script>
Thanks for your help in advance!

Change your listener to do something with the emitted value. I see the parent already has a selected variable that you maybe intend to use for this purpose:
Event.$on('selected', (selectedOption) => {
this.selected = selectedOption;
this.appselected = true;
});
The selectedOption is the value emitted from the child.

Related

VueJS: How to use Google places API with multiple refs

I'm using the Google places API for my work and everything works fine. However, I have a unique scenario where I need to have more than one delivery address, hence I'll need to make Google place API works that way.
Here is my current code:
<template>
<div>
<div v-for="(search, index) in searchInput" :key="index">
<input type="text" ref="search" v-model="search.city">
</div>
<button type="button" #click="addMore">Add more</button>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
location: null,
searchInput: [
{
city: ""
}
]
}),
mounted() {
window.checkAndAttachMapScript(this.initLocationSearch);
},
methods: {
initLocationSearch() {
let autocomplete = new window.google.maps.places.Autocomplete(
this.$refs.search
);
autocomplete.addListener("place_changed", function() {
let place = autocomplete.getPlace();
if (place && place.address_components) {
console.log(place.address_components);
}
});
},
addMore() {
this.searchInput.push({ city: "" });
}
}
};
</script>
I get this error from the API: InvalidValueError: not an instance of HTMLInputElement and b.ownerDocument is undefined
How do I make the refs unique for the individual item that I add and then pass it to the initLocationSearch method? Please, any help would be appreciated.
Her is a Codesandbox demo
Given the details you provided for the complete scenario, here is how I would do it.
I would use a simple counter to keep track of the number of inputs and set its initial value to 1 and also use it to display the inputs.
<div v-for="(n, index) in this.counter" :key="index">
<input type="text" ref="search">
</div>
Then bind the Autocomplete widget to the last added input, based on the counter.
autocomplete = new window.google.maps.places.Autocomplete(
this.$refs.search[this.counter - 1]
);
And use your addMore() method to increment the counter.
addMore() {
this.counter++;
}
Use updated() for whenever a new input is added to the DOM to trigger the initLocationSearch() method.
updated() {
this.initLocationSearch();
},
On place_changed event, update the list of selected cities based on the various input values.
this.selectedCities = this.$refs["search"].map(item => {
return { city: item.value };
});
This way you always have an up to date list of cities, whatever input is changed. Of course you would need to handle emptying an input and probably other edge cases.
Complete code:
<template>
<div>
<div v-for="(n, index) in this.counter" :key="index">
<input type="text" ref="search">
</div>
<button type="button" #click="addMore">Add more</button>
<hr>Selected cities:
<ul>
<li v-for="(item, index) in this.selectedCities" :key="index">{{ item.city }}</li>
</ul>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
selectedCities: [],
counter: 1
}),
mounted() {
window.checkAndAttachMapScript(this.initLocationSearch);
},
updated() {
this.initLocationSearch();
},
methods: {
setSelectedCities() {
this.selectedCities = this.$refs["search"].map(item => {
return { city: item.value };
});
},
initLocationSearch() {
let self = this,
autocomplete = new window.google.maps.places.Autocomplete(
this.$refs.search[this.counter - 1],
{
fields: ["address_components"] // Reduce API costs by specifying fields
}
);
autocomplete.addListener("place_changed", function() {
let place = autocomplete.getPlace();
if (place && place.address_components) {
console.log(place);
self.setSelectedCities();
}
});
},
addMore() {
this.counter++;
}
}
};
</script>
CodeSandbox demo
You can dynamically bind to ref. Something like :ref="'search' + index"
<template>
<div>
<div v-for="(search, index) in searchInput" :key="index">
<input type="text" :ref="'search' + index" v-model="search.city">
</div>
<button type="button" #click="addMore">Add more</button>
</div>
</template>
Then in addMore, before creating a pushing on a new object to searchInput, grab the last index in searchInput. You can then get the newly created ref and pass that to initLocationSearch.
initLocationSearch(inputRef) {
let autocomplete = new window.google.maps.places.Autocomplete(
inputRef
);
autocomplete.addListener("place_changed", function() {
let place = autocomplete.getPlace();
if (place && place.address_components) {
console.log(place.address_components);
}
});
},
addMore() {
const lastInputRef = this.$refs['search' + this.searchInput.length - 1];
this.initLocationSearch(lastInputRef);
this.searchInput.push({ city: "" });
}

Vue.js: draw the table with elements, calling the api for each row

I have a vue component:
<template>
<div class="tableWrapper">
<md-table
class="scheduledListJobList"
v-model="scheduledList"
>
<md-table-row :class="item.status" slot="md-table-row" slot-scope="{item}" #click="open(item)">
<md-table-cell class="nameColumn" md-label="Название задания" to="/upload" >{{ item.name}}</md-table-cell>
<md-table-cell md-label="Номер билда">{{ item.jobNumber }}</md-table-cell>
</md-table-row>
</md-table>
</div>
</template>
<script>
import { mapState } from "vuex";
import {permissionList} from "../../permission/permission";
import {Job} from "../../api";
export default {
name: "gg-jobs-list",
computed: mapState(["scheduledList"]),
mounted: function(){
this.$store.dispatch('GET_SCHEDULED_JOBS');
},
data: function () {
return {
element: null
};
},
methods: {
open(selected) {
this.$router.push({ path: '/jobs/' + selected.routeId});
},
refresh(){
Job.getJobs()
}
}
};
</script>
It has a scheduleList that has the name and id fields.
I need to output the name field to the table, and then call a method that goes to the backend, with each id field for the sheet elements, gets an object and complements the table.
Here is the method that calls the api:
refresh(){
Job.getJobs()
}
getJobs: id => getRequest(`/routes/monitoring/jobs/${id}`, null)
From this method, I should return an object with the start and end fields.
With these fields, I must add each scheduledList element to the tables.
How can I do this? thank you so much for your help.
Add another computed property as v-model directive value :
computed:{
...mapState(["scheduledList"]),
scheduledListRefreshed:{
get(){
return this.scheduledList.map(item=>{
item.jobs=Job.getJobs(item.id);
return item;
},
set(val){
}
}
template :
<template>
<div class="tableWrapper">
<md-table
class="scheduledListJobList"
v-model="scheduledListRefreshed"
>
<md-table-row :class="item.status" slot="md-table-row" slot-scope="{item}" #click="open(item)">
<md-table-cell class="nameColumn" md-label="Название задания" to="/upload" >{{ item.name}}</md-table-cell>
<md-table-cell md-label="Номер билда">{{ item.jobNumber }}</md-table-cell>
</md-table-row>
</md-table>
</div>
</template>

Vue.js : Why I can't bind external property to child props component?

I have a question about Vue.js, I'm stuck on something tricky I guess.
I cannot bind passed property as component property to do some stuff on this data, here is my code, the issue is affecting Plot component.
Here is my dashboard component which is the parent :
<template>
<div>
<div v-if="!hasError && countryData">
<div v-if="loading" id="dashboard" class="ui two column grid sdg-dashboard sdg-text-center active loader">
</div>
<div v-else id="dashboard" class="ui two column grid sdg-dashboard">
<div class="column sdg-text-center">
<MapDisplay :country="countryData" :latitude="latData" :longitude="lonData"/>
</div>
<div class="column">
<TopicSelector v-on:topicSelectorToParent="onTopicSelection" :goals="goalsData"/>
</div>
<div class="two segment ui column row sdg-text-center">
<Plot :topic-selection-data="topicSelectionData"/>
</div>
</div>
<sui-divider horizontal><h1>{{ countryData }}</h1></sui-divider>
</div>
<div v-else>
<NotFound :error-type="pageNotFound"/>
</div>
</div>
</template>
<script>
import NotFound from '#/views/NotFound.vue';
import MapDisplay from '#/components/dashboard/MapDisplay.vue';
import TopicSelector from '#/components/dashboard/TopicSelector.vue';
import Plot from '#/components/dashboard/Plot.vue';
const axios = require('axios');
export default {
name: 'Dashboard',
components: {
NotFound,
MapDisplay,
TopicSelector,
Plot
},
props: {
countryCode: String
},
data: function() {
return {
loading: true,
hasError: false,
country: this.countryCode,
//Country, lat, lon
countryData: null,
latData: null,
lonData: null,
//Goals provided to Topic Selector
goalsData: null,
//Selected topic provided by Topic Selector
topicSelection: null,
//Topic Data provided to Plot component
topicData: null, //All topic data
topicSelectionData: null,
pageNotFound: "Error 500 : Cannot connect get remote data."
}
},
created: function() {
const api = process.env.VUE_APP_SDG_API_PROTOCOL + "://" + process.env.VUE_APP_SDG_API_DOMAIN + ":" + process.env.VUE_APP_SDG_API_PORT + process.env.VUE_APP_SDG_API_ROUTE;
axios.get(api + "/countrycode/" + this.countryCode)
.then(response => {
this.countryData = response.data.data.country;
this.latData = response.data.data.coordinates.latitude;
this.lonData = response.data.data.coordinates.longitude;
this.goalsData = response.data.data.goals.map(goal => {
return {
goal_code: goal["goal code"],
goal_description: goal["goal description"]
}
});
this.topicData = response.data.data.goals;
})
.catch(() => this.hasError = true)
.finally(() => this.loading = false);
},
methods: {
onTopicSelection: function(topic) {
this.topicSelection = topic;
this.topicSelectionData = this.topicData.filter(goal => this.topicSelection.includes(goal["goal code"]));
}
}
}
</script>
<style scoped lang="scss">
#dashboard {
margin-bottom: 3.1vh;
margin-left: 1vw;
margin-right: 1vw;
}
</style>
Here is the Plot component which his the child :
<template>
<div id="plot">
topic data : {{ topicData }}<br>
topicSelectionData : {{ topicSelectionData }}
</div>
</template>
<script>
export default {
name: 'Plot',
props: {
topicSelectionData: Array
},
data: function() {
return {
topicData: this.topicSelectionData //This line is not working =(
}
}
}
</script>
<style scoped lang="scss">
</style>
I can see my data in {{ topicSelectionData }} but when I bind it to topicData, I cannot retrieve the data using {{ topicData }} or doing some stuff inside a method using topicData as input.
Could you provide me some help ?
Regards
You need to assign the value on mounted as follows:
data() {
return {
topicData: ''
}
},
mounted(){
this.topicData = this.topicSelectionData;
}
And in order to update the child when the value changes in the parent:
watch: {
topicSelectionData: function(newValue, oldValue) {
this.topicData = newValue;
}
},

How do you target a button, which is in another component, with a method in App.vue?

I'm making a basic To Do app, where I have an input field and upon entering a task and pressing the "Enter" key the task appears in the list. Along with the task the TodoCard.vue component also generates a button, which I would like to use to delete the task.
I've added a #click="removeTodo" method to the button, but don't know where to place it, in the TodoCard component or in the App.vue file?
TodoCard component:
<template>
<div id="todo">
<h3>{{ todo.text }}</h3>
<button #click="removeTodo(todo)">Delete</button>
</div>
</template>
<script>
export default {
props: ['todo'],
methods: {
removeTodo: function (todo) {
this.todos.splice(this.todos.indexOf(todo), 1)
}
}
}
</script>
App.vue:
<template>
<div id="app">
<input class="new-todo"
placeholder="Enter a task and press enter."
v-model="newTodo"
#keyup.enter="addTodo">
<TodoCard v-for="(todo, key) in todos" :todo="todo" :key="key" />
</div>
</template>
<script>
import TodoCard from './components/TodoCard'
export default {
data () {
return {
todos: [],
newTodo: ''
}
},
components: {
TodoCard
},
methods: {
addTodo: function () {
// Store the input value in a variable
let inputValue = this.newTodo && this.newTodo.trim()
// Check to see if inputed value was entered
if (!inputValue) {
return
}
// Add the new task to the todos array
this.todos.push(
{
text: inputValue,
done: false
}
)
// Set input field to empty
this.newTodo = ''
}
}
}
</script>
Also is the code for deleting a task even correct?
You can send an event to your parent notifying the parent that the delete button is clicked in your child component.
You can check more of this in Vue's documentation.
And here's how your components should look like:
TodoCard.vue:
<template>
<div id="todo">
<h3>{{ todo.text }}</h3>
<button #click="removeTodo">Delete</button>
</div>
</template>
<script>
export default {
props: ['todo'],
methods: {
removeTodo: function (todo) {
this.$emit('remove')
}
}
}
</script>
App.vue:
<template>
<div id="app">
<input class="new-todo"
placeholder="Enter a task and press enter."
v-model="newTodo"
#keyup.enter="addTodo">
<TodoCard v-for="(todo, key) in todos" :todo="todo" :key="key" #remove="removeTodo(key)" />
</div>
</template>
<script>
import TodoCard from './components/TodoCard'
export default {
data () {
return {
todos: [],
newTodo: ''
}
},
components: {
TodoCard
},
methods: {
addTodo: function () {
// Store the input value in a variable
let inputValue = this.newTodo && this.newTodo.trim()
// Check to see if inputed value was entered
if (!inputValue) {
return
}
// Add the new task to the todos array
this.todos.push(
{
text: inputValue,
done: false
}
)
// Set input field to empty
this.newTodo = ''
}
},
removeTodo: function(key) {
this.todos.splice(key, 1);
}
}
</script>

Component Autocomplete VueJS

I want to create an autocomplete component, so I have the following code.
<Input v-model="form.autocomplete.input" #on-keyup="autocomplete" />
<ul>
<li #click="selected(item, $event)" v-for="item in form.autocomplete.res">
{{item.title}}
</li>
</ul>
autocomplete(e){
const event = e.path[2].childNodes[4]
if(this.form.autocomplete.input.length > 2){
this.Base.get('http://localhost:3080/post/search/post', {
params: {
q: this.form.autocomplete.input
}
})
.then(res => {
this.form.autocomplete.res = res.data
if(this.form.autocomplete.res.length > 0)
event.style.display = 'block'
})
}
},
selected(item, e){
this.form.autocomplete.item = item
console.log(e)
}
however, how would I do to have the return after selecting my item in the main file?
Ex:
Home.vue
<Autocomplete :url="www.url.com/test" />
When selecting the item I want from my autocomplete, how do I get the return from it and store it in that file, as if I were using v-model?
As Vue Guide said:
Although a bit magical, v-model is essentially syntax sugar for
updating data on user input events, plus special care for some edge
cases.
Then at Vue Using v-model in Components,
the <input> inside the component must:
Bind the value attribute to a value prop
On input, emit its own custom input event with the new value
Then follow above guide, one simple demo will be like below:
Vue.config.productionTip = false
Vue.component('child', {
template: `<div>
<input :value="value" #input="autocomplete($event)"/>
<ul v-show="dict && dict.length > 0">
<li #click="selected(item)" v-for="item in dict">
{{item.title}}
</li>
</ul>
</div>`,
props: ['value'],
data() {
return {
dict: [],
timeoutControl: null
}
},
methods: {
autocomplete(e){
/*
const event = e.path[2].childNodes[4]
if(this.form.autocomplete.input.length > 2){
this.Base.get('http://localhost:3080/post/search/post', {
params: {
q: this.form.autocomplete.input
}
})
.then(res => {
this.form.autocomplete.res = res.data
if(this.form.autocomplete.res.length > 0)
event.style.display = 'block'
})
}*/
clearTimeout(this.timeoutControl)
this.timeoutControl = setTimeout(()=>{
this.dict = [{title:'abc'}, {title:'cde'}]
}, 1000)
this.$emit('input', e.target.value)
},
selected(item){
this.selectedValue = item.title
this.$emit('input', item.title)
}
}
})
new Vue({
el: '#app',
data() {
return {
testArray: ['', '']
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<child v-model="testArray[0]"></child>
<child v-model="testArray[1]"></child>
<div>Output: {{testArray}}</div>
</div>

Categories

Resources