I have a component that emit event through a bus as indicated below. The same component need to be included twice on another component. I want the events emitted to populate different variables;
//component.vue
<template>
<div>
Hello there?
<a #click="changed">New</a>
<ol>
<li v-for="option in list">
<div class='row justify-content-start'>
<div class='col-sm-6'><input v-model="option.value" type='text' placeholder="key"/></div>
<div class='col-sm-6'><input v-model="option.name" type='text' placeholder="Name"/></div>
</div>
</li>
</ol>
</div>
</template>
<script>
export default{
props:['options','iscolumn'],
data(){
return {list:this.options,item:{name:'',value:''}}
},
methods:{
changed(){
$bus.$emit('add-option',this.item,this.iscolumn);
}
}
}
</script>
/** root.vue **/
<template>
<div>
<h3>Rows</h3>
<div><rows :options="rows" :iscolumn="false"/></div>
<h3>Columns</h3>
<div><rows :options="columns" :iscolumn="true" /></div>
</div>
</template>
<script>
export default{
components:{'rows':require('./component')},
data(){
return {
columns:[],rows:[]
}
},
created(){
this.$bus.$on('add-option',(option,iscolumn)=>{
if (is_column) {this.columns.push(option);}
else this.rows.push(option);
})
}
}
</script>
When I click on the New from root both columns and rows get populated.
Looking for case where each of the component are independent, can't understand how they are sharing variables.
Any assistance will be appreciated.
Assign unique key attributes to the rows components:
<template>
<div>
<h3>Rows</h3>
<div><rows key="rows1" :options="rows" :iscolumn="false"/></div>
<h3>Columns</h3>
<div><rows key="rows2" :options="columns" :iscolumn="true" /></div>
</div>
</template>
Related
I have a component that generates a random item every time I access the random page. Each time I refresh the page a new random item is generated. I would like to generate a new random item every time I click the button 'pick another', but I'm not entirely sure how this can be done. Any help would be greatly appreciated.
Random.vue
<template>
<div class="details" v-for="item in items" v-bind:key="item.id">
<div class="details-primary u-center-text">
<h1 class="heading-secondary">{{item.name}}</h1>
<p class="tagline--main">{{item.tagline}}</p>
</div>
<div class="details-secondary u-margin-top-big">
<div class="info">
<span class="info__detail info--title">Vol</span>
<span class="info__detail info--spec">{{item.abv}}%</span>
</div>
<img class="details-image" :src='item.image_url' alt="">
<div class="info">
<span class="info__detail info--title">Amount</span>
<span class="info__detail info--spec">1ltr</span>
</div>
</div>
</div>
<div class="rand-gen">
Pick another
</div>
</template>
<script lang="ts">
import {Options, Vue} from 'vue-class-component'
import axios from 'axios';
#Options({
data() {
return{
items: []
}
},
mounted() {
axios.get('https://api.punkapi.com/v2/beers/random')
.then(res => this.items = res.data)
.catch(err => console.log(err));
}
})
export default class Random extends Vue {}
</script>
you have to add #click function and method
html should like this
Pick another
and the method is
methods: {
generate() {
//your code
}
}
I have an API call that loads on my App.vue that populates my vuex store's state. The App.vue by default loads a Home.vue that displays images based on the store's state. The images load, but throw a lot of console errors before the state is populated. I'm not sure what the best logic is, in general, to delay loading VIEWS before the data they depend on is finished loading. Existing answers make sense for components but I can't bind data to the router-view, and don't think passing it in params makes sense. I'm a n00b.
//App.vue
<template>
<div id="app">
<div id="nav">
<div id="nav-logo"></div>
<div id="nav-links">
<router-link to="/">Home</router-link>
<router-link to="/pokemon">Pokemon</router-link>
</div>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
created(){
this.init();
},
methods:{
init(){
this.$store.dispatch('fetchPokemon', 'gen1');
}
}
}
</script>
//Home.vue
<template>
<div>
<div id="pokemonAFront">
<img :src="pokeImg[randomA].sprites.front_default" alt="">
</div>
<div id="pokemonABack">
<img :src="pokeImg[randomA].sprites.back_default" alt="">
</div>
</div>
</template>
<script>
export default {
data(){
return{
randomA: Math.floor(Math.random()* 20),
},
computed:{
pokeImg(){
return this.$store.state.pokemon
}
}
</script>
//store/index.js
state:{
pokemon:[]
},
mutations: {
SET_POKEMON(state, pokemon){
state.pokemon = pokemon;
}
},
actions: {
fetchPokemon(context, currentGen){
context.commit('SET_POKEMON', pokeData.fetchPokemon(currentGen)) //api call
}
}
What logic works best for delaying loading views/components when their vuex dependencies haven't loaded yet?
The simplest is to render the dom only after the pokeImg gets populated from API:
<div v-if="pokeImg.length > 0">
<div id="pokemonAFront">
<img :src="pokeImg[randomA].sprites.front_default" alt="">
</div>
<div id="pokemonABack">
<img :src="pokeImg[randomA].sprites.back_default" alt="">
</div>
</div>
I remember I have seen once how to put the values in the html text area after importing components in VUE.
I'm not sure there is a way to do that or I just remember things in a wrong way.
my code is as below.
<template>
<div class="container">
<div class="row">
<Heading></Heading>
</div>
<hr>
<div class="row">
<div class="col-xs-12 col-sm-6">
<ul class="list-group">
<comp v-for='(value,index) in listing' :key='index'>{{value}}</comp>
</ul>
</div>
<serverstat></serverstat>
</div>
<hr>
<div class="row">
<footing></footing>
</div>
</div>
</template>
<script>
import Heading from './assets/Heading.vue';
import comp from './assets/comp.vue';
import serverstat from './assets/serverstatus.vue';
import footing from'./assets/footing.vue';
export default {
data() {
return {
listing: ['max','toms','judy','michael','dumdum']
}
},
components: {
Heading,comp,serverstat,footing
},
};
</script>
<style>
</style>
-comp-
<template>
<li class="list-group-item">
</li>
</template>
<script>
export default {
}
</script>
<style>
</style>
After I render this,
it doesn't show {{value}}. It only shows blank .
How do I insert the {{value}} within the html element?
Thank you in advance.
Since you are entering a value inside of a component, you can render it by using a slot in your component like this:
<template>
<li class="list-group-item">
<slot />
</li>
</template>
<comp v-for='(value,index) in listing' :key='index'>
<slot>{{ value }} </slot>
</comp>
Then in comp component use slot as
<slot/>
Not including the approach for props as you don't want to use that. Use the link above to learn more about slots.
When you use v-for it calls all the value from an array and :key='index' defines each object row from an array. If your object listing consists of firstname, lastname as your object then the value you want to print will be {{value.firstname}}. You are missing object name in value.
Can you try this once :
<comp v-for='(value,index) in listing' :key='index'>{{value.index}}</comp>
I have a TODO app and want to pass by props from one component to another an array of objects. An object is added every time you click a button but I'm having trouble with it. The problem is that the property value becomes the same for every single object added to the array. It seems like it's not saving correctly each tareas.tarea data.
App.vue
<template>
<div>
<Header></Header>
<AgregarTarea #tareaAgregada="agregarTarea"></AgregarTarea>
<div class="container">
<div class="columns">
<div class="column">
<Lista :tareas = 'tareas' #eliminarItem="eliminarTarea"></Lista>
<!-- here i pass through props the array of objects -->
</div>
<div class="column">
<TareaFinalizada></TareaFinalizada>
{}
</div>
</div>
</div>
</div>
</template>
<script>
import Header from './components/Header'
import AgregarTarea from './components/AgregarTarea'
import Lista from './components/Lista'
import TareaFinalizada from './components/TareaFinalizada'
export default {
data(){
return {
tareas:[]
}
},
components: {
Header,
AgregarTarea,
Lista,
TareaFinalizada
},
methods: {
agregarTarea(data){
//add new object to the array
this.tareas.push(data)
},
eliminarTarea(data) {
this.tareas.splice(data.id, 1);
}
}
};
</script>
AgregarTarea.vue || Here is where i add a new ToDo
<template>
<div class="container">
<input class="input" type="text" placeholder="Text input" v-model="tareas.tarea">
<button class="button is-primary" #click="agregarTarea">Agregar Tarea</button>
</div>
</template>
<script>
export default {
data(){
return {
tareas: {
tarea:'',
id:null,
editar:false
}
}
},
methods: {
agregarTarea(){
this.$emit('tareaAgregada', this.tareas)
this.tareas.tarea = ' ';
}
}
}
</script>
Lista.vue || And here is where i display the ToDo's
<template>
<div>
<div class="list is-hoverable">
<ul>
<li v-for="(tarea, index) in tareas" :key="index">
<a class="list-item has-text-centered" #click="editarTexto(index)">
{{ tarea }}
<div class="editar" v-if="editar">
<input class="input" type="text" placeholder="Text input" v-model="nuevaTarea">
</div>
</a>
<button class="button is-danger" #click="eliminarItem(index)">Eliminar</button>
<div><input type="checkbox"> Finalizada</div>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
props:['tareas'],
data(){
return {
nuevaTarea: ' ',
editar:false,
}
},
methods: {
eliminarItem(index){
this.$emit('eliminarItem', index)
},
editarTexto(){
this.editar = true
}
}
}
</script>
<style scoped>
</style>
JavaScript objects are passed by reference (not cloned by value). Each time you $emit the tareas object from AgregarTarea.vue, it's the same object reference as before, even if the properties have changed. So all of the objects in your tareas array in App.vue are the same object.
To fix this, change AgregarTarea.vue to $emit a clone each time:
methods: {
agregarTarea(){
this.$emit('tareaAgregada', Object.assign({}, this.tareas)) // clone
this.tareas.tarea = ' ';
}
}
(This is a shallow clone and would not work properly if this.tareas had nested objects, but it doesn't.)
Option #2
Here's a different way that works easily for nested objects:
new Vue({
el: "#app",
data(){
return {
tareas: null // <-- It's not filled here
}
},
methods: {
resetTareas() { // <-- it's filled here instead
this.tareas = {
tarea:'',
id:null,
editar:false
}
},
agregarTarea(){
this.$emit('tareaAgregada', this.tareas);
this.resetTareas(); // <-- Create a brand new object after emitting
}
},
created() {
this.resetTareas(); // <-- This is for the first one
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Tarea: <input type="text" v-model="tareas.tarea" /><br /><br />
<button #click="agregarTarea">Emit</button><br /><br />
Object: {{ tareas }}
</div>
Since resetTareas creates a brand new object every time, you don't have to worry about cloning anything, and it works even if tareas is a complex nested object.
I have a brand new app in vue.js. I want to change the data value of the app.vue using the checkbox checked used in the child component how I will do this the code I' using in both the files is:-
component file:-
<template>
<div>
<h3>Edit the user</h3>
<p>Local: {{ $route.query.local }}</p>
<p>Number is:- {{ $route.query.q }}</p>
<label><input type="checkbox" #click="change()">customizer</label>
</div>
</template>
<script>
export default{
props:["changeParentStatus"],
methods:{
change() {
this.active = !this.active
console.log(this.active)
this.changeParentStatus(this.active);
}
}
}
</script>
app.vue file
<template>
<div :class="[{ 'active': active }]">
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<h1>Routing</h1>
<hr>
<app-header></app-header>
<router-view :changeParentStatus="changeStatus"></router-view>
</div>
</div>
</div>
</template>
<script>
import AppHeader from "./components/Header.vue";
export default {
data(){
return{
active: true
}
},
methods:{
changeStatus(active){
this.active=active
}
},
components:{
appHeader: AppHeader
}
}
</script>
<style>
.active{
background: black;
}
</style>
How will I change the value of the app.vue data active to true or false by changing the checkbox used in the component file. Can anybody please help me to do this.
Folder structure is:-
src---> app.vue
components---->users----->userEdit.vue (component file)
you can pass a function as an attribute to the child component
<app-header :changeParentStatus="changeStatus"></app-header>
parent
callback
<script>
import AppHeader from "./components/Header.vue";
export default {
data(){
return{
active: true
}
},
methods:{
changeStatus(active){
this.active=active
}
},
components:{
appHeader: AppHeader
}
}
</script>
now call "changeParentStatus" from child change function
<script>
export default{
props:["changeParentStatus"],
methods:{
change() {
this.active = !this.active
console.log(this.active)
this.changeParentStatus(this.active);
}
}
}
</script>
Looks like you want to pass the checkbox value from child to parent. For this define event on parent component and emit that event from child component.
In Parent handle event like this:
<router-view #changeParentStatus="changeStatus"></router-view>
The ChangeStatus is event/method so we defined using v-on: (or #shorthand)
Next, emit event from child component:
<label>
<input type="checkbox"
#click="$emit('changeParentStatus', $event.target.checked)">
customizer</label>
More info: Vue.JS Guide