I have the following code and it works by refreshing the page it works fine, but not when clicking on the nav.
How can i achieve that when i click on users, the method fetchData will be executed? So i can see the console.log and the json data.
Navigation:
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<router-link v-for="item in items" v-if="item.navitems && item.navitems.navitem" :to="item.navitems.navitem.url" tag="li" active-class="active" exact><a>{{item.navitems.navitem.name}}</a></router-link>
Content.vue
<template>
<div>
<div class="container">
<h1>{{ slug }}</h1>
<ul v-if="items && items.length">
<li v-for="item of items">
<p><strong>{{item.name}}</strong></p>
<p>{{item.email}}</p>
</li>
</ul>
</div>
</div>
</template>
<script>
export default{
props: ['slug'],
data: () => ({
items: []
}),
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
var self = this;
console.log(this.slug);
$.get( 'http://jsonplaceholder.typicode.com/' + this.slug, function( data ) {
self.items = data;
console.log(data);
});
}
}
}
</script>
Changed created into mounted and add watch.
watch: {
'$route.params.slug'(newSlug, oldSlug) {
this.fetchData(newId);
}
}
Related
How can I pass the page_id to the Sidebar component method highlightNode(), because I want to highlight a newly added item. My current code is the page id is undefined.
This is my code & structure.
my root component is Sidebar.vue
<template>
<div>
<ul>
<li v-for="page in pages">
<div :class="{ 'highlight': highlightedNode == page.id }">
<router-link :to="'/view/' + page.id" #click.native="highlightNode(page.id)">
<span v-title="page.title"></span>
</router-link>
</div>
</li>
</ul>
</div>
</template>
export default {
data () {
return {
pages: [],
highlightedNode: null
}
},
mounted() {
this.getPages()
this.$root.$refs.Sidebar = this
},
methods: {
getPages() {
axios.get('/get-pages').then(response => {
this.pages = response.data
});
},
highlightNode(id) {
this.highlightedNode = id
},
}
}
my add new Page component AddNewPage.vue
<template>
<div>
<div class="main-header">
<div class="page-title">
<input type="text" v-model="page.title" class="form-control">
</div>
</div>
<div class="main-footer text-right">
<button class="btn btn-success btn-sm" #click="saveChanges()">Save and Publish</button>
</div>
</div>
</template>
export default {
data () {
return {
page: {
title: null,
},
}
},
mounted() {
//
},
methods: {
saveChanges() {
axios.post('/store-new-filter', this.page)
.then(response => {
const id = response.data.id // return page id
this.$root.$refs.Sidebar.highlightNode(id) // <-- this line, I want to pass page id to hightlight the newly added page.
})
.catch( error => {
})
},
}
}
Or any alternative way to achieve my expected output.
Thanks in advance.
I have a simple situation that I want to render cart-badge based on window width value but it always show the last one even though windowWidth does change the value. Please advise me what to do !
<template v-if="windowWidth>=1024">
<div class="nav-user-account"> {{windowWidth}}
<div class="nav-cart nav-cart-box">
<span class="text hidden-sm">Cart</span>
<span class="cart-number" id="nav-cart-num">{{cartItemCount}}</span>
</div>
</div>
</template>
<template v-if="windowWidth<1024">
<a href="#" style="color:#ff6a00" class="icon-cart">
{{windowWidth}}
<i class="fa fa-shopping-cart fa-2x" aria-hidden="true"></i>
<span class="cart-num">2</span>
</a>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
data() {
return {
windowWidth: window.innerWidth,
}
},
computed: {
...mapGetters('cart', {
cartItemCount: 'getShoppingCartItemsCount'
})
},
mounted() {
this.$nextTick(() => {
window.addEventListener('resize', () => {
this.windowWidth= window.innerWidth
});
})
},
}
</script>
UPDATED: as Tony19 pointed out, i need a master template outside of these 2 template.
<template>
<div>
<template v-if="windowWidth>=1024">...</template>
<template v-else></template>
</div>
</template>
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.
My view like this :
#foreach($leagues as $league)
<a #click="$refs.leagues.changeLeague({{ $league->id }})">
{{ $league->name }}
</a>
#endforeach
...
<top-league class="slick" league-id="{{ $league_id }}" ref="leagues"></top-league>
My top league component vue like this :
<template>
<div class="row">
<div class="col-md-3" v-for="item in items">
<div class="panel panel-default">
<div class="panel-image">
<a :href="baseUrl+'/leagues/'+item.id+'/'+item.name"
:style="{backgroundImage: 'url(' + baseUrl + '/img/leagues/'+item.photo+ ')'}">
</a>
</div>
</div>
</div>
</div>
</template>
<script>
...
export default {
...
props: ['leagueId'],
created() {
$('.slick').slick({slidesToShow: 3, infinite: false});
this.getTopLeague([{league_id: this.leagueId}]) // this is ajax if load first
},
computed: {
...mapGetters([
'getListLeague'
]),
items() {
const n = ['getListLeague']
return this[n[0]] // this is response ajax // exist 5 league
}
},
methods: {
...mapActions([
'getTopLeague'
]),
changeLeague(leagueId) {
this.getTopLeague([{league_id: leagueId}]) // this is ajax if a link clicked
}
}
}
</script>
When loaded the first time, there are 5 items of data displayed in the form of sliders. I tried putting this code : $('.slick').slick({slidesToShow: 3, infinite: false}); in created, but there was an error
If the code executed, there exist error like this :
[Vue warn]: Error in created hook: "TypeError: $(...).slick is not a
function"
How can I solve it?
Ok, try this.
<template>
<div ref="slick">
<div class="row">
<div class="col-md-3" v-for="item in items">
<div class="panel panel-default">
<div class="panel-image">
<a :href="baseUrl+'/leagues/'+item.id+'/'+item.name"
:style="{backgroundImage: 'url(' + baseUrl + '/img/leagues/'+item.photo+ ')'}">
</a>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
...
export default {
...
props: ['leagueId'],
mounted() {
$(this.$el).slick({slidesToShow: 3, infinite: false});
this.getTopLeague([{league_id: this.leagueId}]) // this is ajax if load first
},
computed: {
...mapGetters([
'getListLeague'
]),
items() {
const n = ['getListLeague']
return this[n[0]] // this is response ajax // exist 5 league
}
},
methods: {
...mapActions([
'getTopLeague'
]),
changeLeague(leagueId) {
this.getTopLeague([{league_id: leagueId}]) // this is ajax if a link clicked
}
}
}
</script>
My view like this :
#foreach($leagues as $league)
<a data-toggle="tab" #click="$refs.leagues.changeLeague({{ $league->id }})">
{{ $league->name }}
</a>
#endforeach
...
<div class="tab-pane active">
<top-league class="slick" league-id="{{ $league_id }}" ref="leagues"></top-league>
</div>
My top league component vue like this :
<template>
<div class="row">
<div class="col-md-3" v-for="item in items">
<div class="panel panel-default">
<div class="panel-image">
<a :href="baseUrl+'/leagues/'+item.id+'/'+item.name"
:style="{backgroundImage: 'url(' + baseUrl + '/img/leagues/'+item.photo+ ')'}">
</a>
</div>
</div>
</div>
</div>
</template>
<script>
...
export default {
...
props: ['leagueId'],
mounted(){
setTimeout( function(){
$('.slick').not('.slick-initialized').slick({slidesToShow: 3, infinite: false});
} , 10000 );
},
created() {
this.getTopLeague([{league_id: this.leagueId}]) // this is ajax if load first
},
computed: {
...mapGetters([
'getListLeague'
]),
items() {
const n = ['getListLeague']
return this[n[0]] // this is response ajax // exist 5 league
}
},
methods: {
...mapActions([
'getTopLeague'
]),
changeLeague(leagueId) {
this.getTopLeague([{league_id: leagueId}]) // this is ajax if a link clicked
setTimeout( function(){
$('.slick').not('.slick-initialized').slick({slidesToShow: 3, infinite: false});
console.log('test')
} , 10000 );
}
}
}
</script>
When loaded the first time, there are 5 items of data displayed in the form of sliders. And the slider works. But if I click the another tab. For example I click League B, the slider not works. Whereas the result of console.log('test') had run
How can I solve it?