vue-carousel goToPage to programmatically change to selected page - vue.js

I'm passing a collection of locations into vue-carousel. I'm using the same collection in a couple of other places on the page, emitting the selected location to the root, which is where the locations and selected location are stored, in an eventHub.
The tricky part was getting the carousel to move to the right page - I'm showing three locations at a time in larger viewports and just one on smaller, using the perPageCustom option. I create keys in the api in laravel and based on the size of the window, I'm moving to the right page and it all works, but when it loads I get an error because the ref doesn't exist when the watcher first fires off. I know that's the issue, but I'm not sure how to have a watcher for when the location changes, that doesn't watch when the page loads... perhaps using the mount?
My component:
<template>
<div>
<h3>Locations ({{locations.length}})</h3>
<p class="lead">Serving California in the greater Sacramento and Los Angeles areas.</p>
<carousel v-if="locations.length > 0" ref="locations-carousel" :scrollPerPage="true" :perPage="1" :perPageCustom="[[480, 1], [768, 3]]" v-on:pageChange="pageChange">
<slide v-for="loc in locations" :key="loc.id">
<div class="card" style="width: 18rem;" v-bind:class="{ closest: loc.is_closest, active: loc.id == location.id }">
<img v-on:click="changeLocation(loc.id)" v-if="loc.is_comingsoon === 0" class="card-img-top" :src="'/assets/images/location_'+loc.pathname+'.jpg'" alt="Card image cap">
<img v-on:click="changeLocation(loc.id)" v-if="loc.is_comingsoon === 1" class="card-img-top" :src="'/assets/images/coming-soon.png'" alt="Card image cap">
<div class="card-body">
<h5 class="card-title" v-on:click="changeLocation(loc.id)">{{ loc.name }}</h5>
<p class="card-text">{{ loc.address }}<br>{{ loc.city_name }}<br>{{ loc.phone | phone }}</p>
<div class="btn-group" role="group" aria-label="Location Buttons">
<a class="btn btn-outline btn-default" :href="'tel:'+ loc.phone"><font-awesome-icon icon="phone"></font-awesome-icon> call</a>
<a class="btn btn-outline btn-default" :href="loc.map"><font-awesome-icon icon="globe"></font-awesome-icon> map</a>
<a class="btn btn-outline btn-default" v-on:click="changeLocation(loc)" v-bind:class="{ active: loc.id == location.id }"><font-awesome-icon icon="star"></font-awesome-icon> pick</a>
</div>
<p class="card-text">{{ loc.note }}</p>
<span class="badge badge-closest" v-if="loc.is_closest"><font-awesome-icon icon="map-marker"></font-awesome-icon> closest detected</span>
<span class="badge badge-active" v-if="loc.id == location.id"><font-awesome-icon icon="star"></font-awesome-icon> selected <font-awesome-icon icon="angle-double-down" :style="{ color: 'white' }"></font-awesome-icon></span>
</div>
</div>
</slide>
</carousel>
<font-awesome-icon icon="spinner" size="lg" v-if="locations.length < 1"></font-awesome-icon>
</div>
</template>
<script>
Vue.filter('phone', function (phone) {
return phone.replace(/[^0-9]/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
});
import { Carousel, Slide } from 'vue-carousel';
var axios = require("axios");
export default {
name: 'locations-carousel',
props: ['location', 'pg', 'locations'],
components: {
Carousel,
Slide
},
data() {
return {
debounce: null,
subs: {},
clear: 0
};
},
watch: {
location: function(newVal, oldVal) { // watch it
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
console.log('key: '+this.location.key);
if( window.innerWidth > 481 ) {
if( this.location.pg == 1 ) {
this.$refs['locations-carousel'].goToPage(-0);
} else {
this.$refs['locations-carousel'].goToPage(1);
}
} else {
this.$refs['locations-carousel'].goToPage(this.location.key);
}
}
},
methods: {
pageChange(i){
console.log('current Index', i);
},
changeLocation(location) {
this.$eventHub.$emit('location-loaded', location);
}
}
}
</script>
The error I'm getting:
[Vue warn]: Error in callback for watcher "location": "TypeError:
Cannot read property 'goToPage' of undefined"
found in
---> <LocationsCarousel> at resources/assets/js/components/LocationsCarousel.vue
<Root>
TypeError: Cannot read property 'goToPage' of undefined
at VueComponent.location (app.js?v=0.1:53288)
at Watcher.run (app.js?v=0.1:3937)
at flushSchedulerQueue (app.js?v=0.1:3685)
at Array.<anonymous> (app.js?v=0.1:2541)
at flushCallbacks (app.js?v=0.1:2462)

Perhaps you can check first to see if this.$refs['locations-carousel'] exists before accessing its properties/methods ..
watch: {
location: function(newVal, oldVal) { // watch it
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
console.log('key: ' + this.location.key);
const locationsCarousel = this.$refs['locations-carousel']
if (window.innerWidth > 481) {
if (this.location.pg == 1) {
locationsCarousel && locationsCarousel.goToPage(-0);
} else {
locationsCarousel && locationsCarousel.goToPage(1);
}
} else {
locationsCarousel && locationsCarousel.goToPage(this.location.key);
}
}
},

Related

Including text when an image/icon is shown

At the moment I am trying to include different text when an image and/or icon shows on the page. Here is the code for the vue file:
<template>
<div class="profile">
<div
:class="{
'flags--relevant': hasFlagType('medication'),
'flags--active': flag == 'medication'
}"
class="flags"
#click="setFlag('medication')"
>
<medication-icon
:class="[
hasFlagType('medication')
? 'medication-icon--focus'
: 'medication-icon--blur',
]"
/>
</div>
<div
:class="{
'flags--relevant': hasFlagType('condition'),
'flags--active': flag == 'condition'
}"
class="flags"
#click="setFlag('condition')"
>
<treatment-icon
:class="[
hasFlagType('condition')
? 'treatment-icon--focus'
: 'treatment-icon--blur',
]"
/>
</div>
<div
:class="{
'flags--relevant': hasFlagType('translator'),
'flags--active': flag == 'translator',
}"
class="flags"
#click="setFlag('translator')"
>
<foreign-dialect-icon
:class="[
hasFlagType('translator')
? 'foreign-dialect-icon--focus'
: 'foreign-dialect-icon--blur',
]"
/>
</div>
</div>
</template>
<script>
export default {
components: {
ForeignDialectIcon,
MedicationIcon,
TreatmentIcon,
},
props: {
userFlags: {
type: Array,
default() {
return {};
},
},
},
data() {
return {
flags: this.userFlags,
flag: null,
title: "Requires daily medication",
title2: "Specialist health condition",
title3: "Requires a translator",
};
},
methods: {
hasFlagType(flagType) {
return this.flags[flagType] !== undefined;
},
setFlag(flagType) {
if (this.hasFlagType(flagType)) {
this.flag = flagType;
}
},
resetFlag() {
this.flag = null;
},
},
};
</script>
I have tried outputting the titles in the data section for each icon and they still show even if the icon doesn't show. I need it to output the title when the image is shown and the many attempts I've tried haven't worked so was wondering how I am able to solve this?
Assuming the title should only appear when the corresponding icon is focused, you could use the same condition (hasFlagType(...)) with v-if to render the title:
<div>
<medication-icon .../>
<span v-if="hasFlagType('medication')">{{ title }}</span>
</div>
<div>
<treatment-icon .../>
<span v-if="hasFlagType('condition')">{{ title2 }}</span>
</div>
<div>
<foreign-dialect-icon .../>
<span v-if="hasFlagType('translator')">{{ title3 }}</span>
</div>

Removing specific object from array keeps removing last item

Here is what I have and I will explain it as much as I can:
I have a modal inside my HTML code as shown below:
<div id="favorites-modal-edit" class="modal">
<div class="modal-background"></div>
<div class="modal-card px-4">
<header class="modal-card-head">
<p class="modal-card-title">Favorites</p>
<button class="delete" aria-label="close"></button>
</header>
<section class="modal-card-body">
<div class="container">
<div id="favorites-modal-edit-wrapper" class="columns is-multiline buttons">
<favorites-edit-component v-for="(favorite, index) in favorites_list" :key="favorite.id" :favorite="favorite" />
</div>
</div>
</section>
<footer class="modal-card-foot">
<button class="button" #click="addItem">
Add Item
</button>
</footer>
</div>
</div>
The id="favorites-modal-edit" is the Vue.js app, then I have the <favorites-edit-component /> vue.js component.
Here is the JS code that I have:
I have my favorites_list generated which is an array of objects as shown below:
const favorites_list = [
{
id: 1,
name: 'Horse',
url: 'www.example.com',
},
{
id: 2,
name: 'Sheep',
url: 'www.example2.com',
},
{
id: 3,
name: 'Octopus',
url: 'www.example2.com',
},
{
id: 4,
name: 'Deer',
url: 'www.example2.com',
},
{
id: 5,
name: 'Hamster',
url: 'www.example2.com',
},
];
Then, I have my vue.js component, which is the favorites-edit-component that takes in the #click="removeItem(this.index) which is coming back as undefined on the index.
Vue.component('favorites-edit-component', {
template: `
<div class="column is-half">
<button class="button is-fullwidth is-danger is-outlined mb-0">
<span>{{ favorite.name }}</span>
<span class="icon is-small favorite-delete" #click="removeItem(this.index)">
<i class="fas fa-times"></i>
</span>
</button>
</div>
`,
props: {
favorite: Object
},
methods: {
removeItem: function(index) {
this.$parent.removeItem(index);
},
}
});
Then I have the vue.js app that is the parent as shown below:
new Vue({
el: '#favorites-modal-edit',
// Return the data in a function instead of a single object
data: function() {
return {
favorites_list
};
},
methods: {
addItem: function() {
console.log('Added item');
},
removeItem: function(index) {
console.log(index);
console.log(this.favorites_list);
this.favorites_list.splice(this.favorites_list.indexOf(index), 1);
},
},
});
The problem:
For some reason, each time I go to delete a item from the list, it's deleting the last item in the list and I don't know why it's doing it, check out what is happening:
This is the guide that I am following:
How to remove an item from an array in Vue.js
The item keeps coming back as undefined each time the remoteItem() function is triggered as shown below:
All help is appreciated!
There is an error in your favorites-edit-component template, actually in vue template, when you want to use prop, data, computed, mehods,..., dont't use this
=> there is an error here: #click="removeItem(this.index)"
=> in addition, where is index declared ? data ? prop ?
you're calling this.$parent.removeItem(index); then in removeItem you're doing this.favorites_list.splice(this.favorites_list.indexOf(index), 1); this means that you want to remove the value equal to index in you array no the value positioned at the index
=> this.favorites_list[index] != this.favorites_list[this.favorites_list.indexOf(index)]
In addition, I would suggest you to modify the favorites-edit-component component to use event so it can be more reusable:
favorites-edit-component:
<template>
<div class="column is-half">
<button class="button is-fullwidth is-danger is-outlined mb-0">
<span>{{ favorite.name }}</span>
<span class="icon is-small favorite-delete" #click="$emit('removeItem', favorite.id)">
<i class="fas fa-times"></i>
</span>
</button>
</div>
</template>
and in the parent component:
<template>
...
<div id="favorites-modal-edit-wrapper" class="columns is-multiline buttons">
<favorites-edit-component
v-for="favorite in favorites_list"
:key="favorite.id"
:favorite="favorite"
#removeItem="removeItem($event)"
/>
</div>
...
</template>
<script>
export default {
data: function () {
return {
favorites_list: [],
};
},
methods: {
...
removeItem(id) {
this.favorites_list = this.favorites_list.filter((favorite) => favorite.id !== id);
}
...
},
};
I would restructure your code a bit.
In your favorites-edit-component
change your removeItem method to be
removeItem() {
this.$emit('delete');
},
Then, where you are using your component (in the template of the parent)
Add an event catcher to catch the emitted "delete" event from the child.
<favorites-edit-component v-for="(favorite, index) in favorites_list" :key="favorite.id" :favorite="favorite" #delete="removeItem(index)"/>
The problem you have right now, is that you are trying to refer to "this.index" inside your child component, but the child component does not know what index it is being rendered as, unless you specifically pass it down to the child as a prop.
Also, if you pass the index down as a prop, you must refer to it as "index" and not "this.index" while in the template.

Nuxt Failed to execute ‘appendChild’ on ‘Node’ when trying to get window size

The problem is that the project must be transferred to Nuxt and some of the code does not work. Namely, the size of the screen must perform actions with the text. Since Nuxt is an SSR, the code cannot be executed on the server side because it does not know the size of the window.
Can I somehow fulfill this idea so that everything works?
I have a project with nuxt and i18n
[nuxt] Error while initializing app DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method.
at Object.Je [as appendChild]
this my component vue
This code is an example of what causes an error.
<template>
<section>
<div>
<h2 class="subtitle" v-html="filterHeadSlogan"></h2>
</div>
</section>
</template>
<script>
export default {
name: 'testapp',
data() {
return {
filterHeadSlogan: '',
windowWidth: 0
}
},
methods: {
getWindowWidth(event) {
this.windowWidth = document.documentElement.clientWidth
var str = "<i>HELLO WORLD</i>"
if (this.windowWidth >= 960) {
this.filterHeadSlogan = str
} else {
this.filterHeadSlogan = str.replace(/<\/?[^>]+(>|$)/g, '')
}
}
},
mounted() {
this.$nextTick(function () {
window.addEventListener('resize', this.getWindowWidth);
//Init
this.getWindowWidth()
})
}
}
</script>
An error occurred because there was no data in the variable. The village appeared, but there was no data and there was a conflict. I created asyncData
async asyncData(){
return {
headSlogan: ""
}
},
Full code
<template>
<div class="westartslogan">
<div class="head-slogan">
<h2 v-html="headSlogan"></h2>
</div>
<h3>{{$t('page.home.wellcom_block_subtitle_left')}}</h3>
<ul>
<li><i class="icon"></i>
<div v-html="$t('page.home.wellcom_block_option_1_left')"></div></li>
<li><i class="icon"></i>
<div v-html="$t('page.home.wellcom_block_option_2_left')"></div></li>
<li><i class="icon"></i>
<div v-html="$t('page.home.wellcom_block_option_3_left')"></div></li>
<li><i class="icon"></i>
<div v-html="$t('page.home.wellcom_block_option_4_left')"></div></li>
<li><i class="icon"></i>
<div v-html="$t('page.home.wellcom_block_option_5_left')"></div></li>
</ul>
<div class="startcalc-btn button-container">
<nuxt-link :to="getLocalizedRoute({ name: 'calculator' })" class="uk-button uk-button-default">{{
$t('page.home.wellcom_button_calculator') }}
</nuxt-link >
</div>
<div class="ourproject-btn uk-hidden#s">
<div class="button-container">
<nuxt-link :to="getLocalizedRoute({ name: 'portfolio' })" class="uk-button uk-button-default">
{{ $t('page.home.wellcom_button_portfolio') }}
</nuxt-link>
</div>
</div>
</div>
</template>
<script>
export default {
async asyncData(){
return {
headSlogan: ""
}
},
name: 'we_can',
data () {
return {
filterHeadSlogan: '',
headSlogan: this.$i18n.t('page.home.wellcom_block_title_left'),
windowWidth: 0
}
},
methods: {
getWindowWidth (event) {
this.windowWidth = document.documentElement.clientWidth
if (this.windowWidth >= 960) {
this.headSlogan = this.headSlogan
} else {
var str = this.headSlogan
this.headSlogan = str.replace(/<\/?[^>]+(>|$)/g, '')
}
}
},
mounted() {
this.$nextTick(function () {
window.addEventListener('resize', this.getWindowWidth);
//Init
this.getWindowWidth()
})
}
}
</script>
<style scoped>
</style>
I was dealing with the same problem.
Do these steps:
Run your project (yarn start).
Open http://localhost:3000/ in Chrome.
In Chrome devtools clear site data in application tab.
Hard reload the page.

Search bar in Vue flickr app not giving expected results

I’m using Vue to create a Flickr app and want to add a search bar so users can search for photos containing tags with their search term.
What i’ve done so far produces some results, but I noticed the photos don’t always include my search term as tags, for example if I search 'cats' the returned items might have the tags 'cat' but not 'cats' and sometimes it doesn't include tags that are even slightly similar.
There's no console errors, so i'm not sure where to find the error.
<template>
<b-container>
<b-row>
<b-col md="12">
<b-input-group size="lg" prepend="Search" class="flickr-search">
<b-form-input v-model="search"></b-form-input>
</b-input-group>
</b-col>
</b-row>
<b-row>
<b-card-group columns>
<b-col v-for="photo in Photos" class="item" md="12">
<b-card :title="photo.title"
:img-src="photo.media.m"
img-alt="Image"
img-top
img-fluid
tag="article"
style="max-width: 20rem;"
class="mb-2">
<span class="item-date">31 May 2017</span>
<hr/>
<p>By <a :href="'https://www.flickr.com/photos/' + photo.author_id" :title="formatAuthor(photo.author)" target="_blank">{{ formatAuthor(photo.author) }}</a></p>
<ul class="tags">
<li v-for="tag in splitTags(photo.tags)" class="item-tag">
<a :href="'https://www.flickr.com/photos/tags/' + tag" target="_blank" class="item-taglink">{{ tag }}</a>
</li>
</ul>
</b-card>
</b-col>
</b-card-group>
</b-row>
</b-container>
</template>
<script>
import jsonp from "jsonp";
export default {
name: 'PhotoFeed',
data: function () {
return {
Photos: [],
apiURL: "https://api.flickr.com/services/feeds/photos_public.gne?format=json",
search: ''
}
},
mounted(){
this.getFlickrFeed();
},
methods: {
getFlickrFeed(){
let jsonp = require('jsonp');
let self = this;
jsonp(this.apiURL, {name: 'jsonFlickrFeed'}, (err, data) => {
if (err) {
console.log(err.message);
}
else {
self.Photos = data.items;
}
})
},
formatAuthor(authorString){
if (authorString) return authorString.split("\"")[1];
return "Author";
},
splitTags(tagsString) {
if (tagsString) return tagsString.split(" ");
}
},
watch: {
search(newVal, oldVal) {
let self = this;
let apiURL = "https://api.flickr.com/services/feeds/photos_public.gne?tags=" + self.search + "&format=json";
let jsonp = require('jsonp');
jsonp(apiURL, {name: 'jsonFlickrFeed'}, (err, data) => {
if (err) {
console.log(err.message);
}
else {
self.Photos = data.items;
}
})
}
}
}
</script>
An error won't be thrown if the flicker API doesn't return any results.
In the UI you can let you users know they can provide a comma separated list of keywords, example cats, cat
You can also check no see if there are any results and display a message if none were found here is just one simple example implementation:
Relevant HTML
<b-card-group columns v-if="Photos.length">
<b-col v-for="photo in Photos" class="item" md="12">
<b-card :title="photo.title"
:img-src="photo.media.m"
img-alt="Image"
img-top
img-fluid
tag="article"
style="max-width: 20rem;"
class="mb-2">
<span class="item-date">31 May 2017</span>
<hr/>
<p>By <a :href="'https://www.flickr.com/photos/' + photo.author_id" :title="formatAuthor(photo.author)" target="_blank">{{ formatAuthor(photo.author) }}</a></p>
<ul class="tags">
<li v-for="tag in splitTags(photo.tags)" class="item-tag">
<a :href="'https://www.flickr.com/photos/tags/' + tag" target="_blank" class="item-taglink">{{ tag }}</a>
</li>
</ul>
</b-card>
</b-col>
</b-card-group>
<b-col md="12" v-else-if="!Photos.length && errorMessage">
<p>{{errorMessage}}</p>
</b-col>
Relevant JS
data: function () {
return {
Photos: [],
apiURL: "https://api.flickr.com/services/feeds/photos_public.gne?format=json",
search: '',
errorMessage: null
}
}
In both getFlickerFeed & watch: search:
if (err) {
self.errorMessage = err.message;
}
else {
self.Photos = data.items;
if (self.Photos.length) {
self.errorMessage = null;
} else {
self.errorMessage = 'No results found for: ' + self.search
}
}

Is it possible to sync Vuejs components displayed multiple times on the same page?

I have a web page that displays items. For each items there is a button (vuejs component) which allow user to toggle (add/remove) this item to his collection.
Here is the component:
<template lang="html">
<button type="button" #click="toggle" name="button" class="btn" :class="{'btn-danger': dAdded, 'btn-primary': !dAdded}">{{ dText }}</button>
</template>
<script>
export default {
props: {
added: Boolean,
text: String,
id: Number,
},
data() {
return {
dAdded: this.added,
dText: this.text,
dId: this.id
}
},
watch: {
added: function(newVal, oldVal) { // watch it
this.dAdded = this.added
},
text: function(newVal, oldVal) { // watch it
this.dText = this.text
},
id: function(newVal, oldVal) { // watch it
this.dId = this.id
}
},
methods: {
toggle: function(event) {
axios.post(route('frontend.user.profile.pop.toggle', {
pop_id: this.dId
}))
.then(response => {
this.dText = response.data.message
let success = response.data.success
this.dText = response.data.new_text
if (success) {
this.dAdded = success.attached.length
let cardPop = document.getElementById('card-pop-'+this.dId);
if(cardPop)
cardPop.classList.toggle('owned')
}
})
.catch(e => {
console.log(e)
})
}
}
}
</script>
For each item, the user can also open a modal, loaded by a click on this link:
<a href="#" data-toggle="modal" data-target="#popModal" #click="id = {{$pop->id}}">
<figure>
<img class="card-img-top" src="{{ URL::asset($pop->img_path) }}" alt="Card image cap">
</figure>
</a>
The modal is also a Vuejs component:
<template>
<section id="pop" class="h-100">
<div class="card">
<div class="container-fluid">
<div class="row">
<div class="col-12 col-lg-1 flex-column others d-none d-xl-block">
<div class="row flex-column h-100">
<div v-for="other_pop in pop.other_pops" class="col">
<a :href="route('frontend.pop.collection.detail', {collection: pop.collection.slug, pop: other_pop.slug})">
<img :src="other_pop.img_path" :alt="'{{ other_pop.name }}'" class="img-fluid">
</a>
</div>
<div class="col active order-3">
<img :src="pop.img_path" :alt="pop.name" class="img-fluid">
</div>
</div>
</div>
<div class="col-12 col-lg-6 content text-center">
<div class="row">
<div class="col-12">
<img :src="pop.img_path" :alt="pop.name" class="img-fluid">
</div>
<div class="col-6 text-right">
<toggle-pop :id="pop.id" :added="pop.in_user_collection" :text="pop.in_user_collection ? 'Supprimer' : 'Ajouter'"></toggle-pop>
</div>
<div class="col-6 text-left">
<!-- <btnaddpopwhishlist :pop_id="propid" :added="pop.in_user_whishlist" :text="pop.in_user_whishlist ? 'Supprimer' : 'Ajouter'"></btnaddpopwhishlist> -->
</div>
</div>
</div>
<div class="col-12 col-lg-5 infos">
<div class="header">
<h1 class="h-100">{{ pop.name }}</h1>
</div>
<div class="card yellow">
<div class="card p-0">
<div class="container-fluid">
<div class="row">
<div class="col-3 py-2">
</div>
<div class="col-6 py-2 bg-lightgray">
<h4>Collection:</h4>
<h3>{{ pop.collection ? pop.collection.name : '' }}</h3>
</div>
<div class="col-3 py-2 bg-lightgray text-center">
<a :href="route('frontend.index') + 'collections/' + pop.collection.slug" class="btn-round right white"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: {
id: Number
},
data() {
return {
pop: {
collection: {
}
}
}
},
ready: function() {
if (this.propid != -1)
this.fetchData()
},
watch: {
id: function(newVal, oldVal) { // watch it
// console.log('Prop changed: ', newVal, ' | was: ', oldVal)
this.fetchData()
}
},
computed: {
imgSrc: function() {
if (this.pop.img_path)
return 'storage/images/pops/' + this.pop.img_path
else
return ''
}
},
methods: {
fetchData() {
axios.get(route('frontend.api.v1.pops.show', this.id))
.then(response => {
// JSON responses are automatically parsed.
// console.log(response.data.data.collection)
this.pop = response.data.data
})
.catch(e => {
this.errors.push(e)
})
// console.log('fetchData')
}
}
}
</script>
Here is my app.js script :
window.Vue = require('vue');
Vue.component('pop-modal', require('./components/PopModal.vue'));
Vue.component('toggle-pop', require('./components/TogglePop.vue'));
const app = new Vue({
el: '#app',
props: {
id: Number
}
});
I would like to sync the states of the component named toggle-pop, how can I achieve this ? One is rendered by Blade template (laravel) and the other one by pop-modal component. But they are just the same, displayed at different places.
Thanks.
You could pass a state object as a property to the toggle-pop components. They could use this property to store/modify their state. In this way you can have multiple sets of components sharing state.
Your component could become:
<template lang="html">
<button type="button" #click="toggle" name="button" class="btn" :class="{'btn-danger': sstate.added, 'btn-primary': !sstate.added}">{{ sstate.text }}</button>
</template>
<script>
export default {
props: {
sstate: {
type: Object,
default: function() {
return { added: false, text: "", id: -1 };
}
}
},
data() {
return {};
},
methods: {
toggle: function(event) {
axios.post(route('frontend.user.profile.pop.toggle', {
pop_id: this.sstate.id
}))
.then(response => {
this.sstate.text = response.data.message
let success = response.data.success
this.sstate.text = response.data.new_text
if (success) {
this.sstate.ddded = success.attached.length
let cardPop = document.getElementById('card-pop-'+this.sstate.id);
if(cardPop)
cardPop.classList.toggle('owned')
}
})
.catch(e => {
console.log(e)
})
}
};
</script>
Live demo
https://codesandbox.io/s/vq8r33o1w7
If you are 100% sure that all toggle-pop components should always have the same state, you can choose to not define data as a function. Just declare it as an object.
data: {
dAdded: this.added,
dText: this.text,
dId: this.id
}
In https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function, it mentions
a component’s data option must be a function, so that each instance
can maintain an independent copy of the returned data object
If Vue didn’t have this rule, clicking on one button would affect the
data of all other instances
Since you want to sync the data of all toggle-pop component instances, you don't have to follow the data option must be a function rule.