I am using Nuxt js SSR for an app that am build, I installed Vue Event plugin but when i emit an event it runs twice at the listener. Created hook runs twice too.
Modules am using:
Axios, Auth, Toast
Child Component
methods: {
initPlaylist(songs) {
console.log(songs)
}
},
mounted () {
this.$events.$on('playAll', data => {
this.initPlaylist(data.songs) //runs twice
})
}
Parent Component
method () {
playAll (songs) {
this.$events.$emit('playAll', songs)
}
}
How can i resolve this issues guys? I need your help.
Maybe you have to call that parent's method on client side only.
you can write code like this to prevent emit on server side:
methods: {
playAll(songs) {
if (process.server) return
this.$events.$emit('playAll', songs)
}
}
or do not call playAll method on server side. (eg: created, mounted...)
You need to off that event first before.
this.$events.$off("playAll");
this.$events.$on('playAll', data => {
this.initPlaylist(data.songs) //runs twice
})
Related
When I dispatch an action in App.vue component in mounted() lifecycle hook, it runs after other components load. I am using async/await in my action and mounted lifecycle hook.
App.vue file
methods: {
...mapActions({
setUsers: "setUsers",
}),
},
async mounted() {
try {
await this.setUsers();
} catch (error) {
if (error) {
console.log(error);
}
}
},
action.js file:
async setUsers(context) {
try {
const response = await axios.get('/get-users');
console.log('setting users');
if (response.data.success) {
context.commit('setUsers', {
data: response.data.data,
});
}
} catch (error) {
if (error) {
throw error;
}
}
},
In Users list component, I need to get users from vuex. So I am using mapGetters to get Users list.
...mapGetters({
getUsers: "getUsers",
}),
mounted() {
console.log(this.getUsers);
},
But the problem is "setting users" console log in running after console logging the this.getUsers.
In Users list component, I can use getUsers in the template but when I try to console log this.getUsers it gives nothing.
How can I run app.vue file before running any other components?
You are using async await correctly in your components. It's important to understand that async await does not hold off the execution of your component, and your component will still render and go through the different lifecycle hooks such as mounted.
What async await does is hold off the execution of the current context, if you're using it inside a function, the code after the await will happen after the promise resolves, and in your case you're using it in the created lifecycle hook, which means that the code inside the mounted lifecycle hook which is a function, will get resolved after the await.
So what you want to do, is to make sure you render a component only when data is received.
Here's how to do it:
If the component is a child component of the parent, you can use v-if, then when the data comes set data to true, like this:
data() {
return {
hasData: false,
}
}
async mounted() {
const users = await fetchUsers()
this.hasData = true;
}
<SomeComponent v-if="hasData" />
If the component is not a child of the parent, you can use a watcher to let you know when the component has rendered. When using watch you can to be careful because it will happen every time a change happens.
A simple rule of thumb is to use watch with variables that don't change often, if the data you're getting is mostly read only you can use the data, if not you can add a property to Vuex such as loadingUsers.
Here's an example of how to do this:
data: {
return {
hasData: false,
}
},
computed: {
isLoading() {
return this.$store.state.app.users;
}
},
watch: {
isLoading(isLoading) {
if (!isLoading) {
this.hasData = true;
}
}
}
<SomeComponent v-if="hasData" />
if you're fetching a data from an API, then it is better to dispatch the action inside of created where the DOM is not yet rendered but you can still use "this" instead of mounted. Here is an example if you're working with Vuex modules:
created() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
await this.$store.dispatch('user/setUsers');
},
},
computed: {
usersGetters() {
// getters here
},
},
Question: Do you expect to run await this.setUsers(); every time when the app is loaded (no matter which page/component is being shown)?
If so, then your App.vue is fine. And in your 'Users list component' it's also fine to use mapGetters to get the values (note it should be in computed). The problem is that you should 'wait' for the setUsers action to complete first, so that your getUsers in the component can have value.
A easy way to fix this is using Conditional Rendering and only renders component when getUsers is defined. Possibly you can add a v-if to your parent component of 'Users list component' and only loads it when v-if="getUsers" is true. Then your mounted logic would also work fine (as the data is already there).
I want to pass some extra data from the ssr server that's present after the middleware has run, and use that on client side middleware. A bit similar to what nuxt already does with vuex.
Documentation at the render:context hook:
Every time a route is server-rendered and before render:route hook. Called before serializing Nuxt context into window.__NUXT__, useful to add some data that you can fetch on client-side.
Now my custom plugin defines some hooks as stated in the documentation, but not all seem to be called properly:
module.exports = function() {
this.nuxt.hook('render:route', (url, result, context) => {
console.log('This one is called on every server side rendering')
}
this.nuxt.hook('renderer', renderer => {
console.log('This is never called')
}
this.nuxt.hook('render:context', context => {
console.log('This is only called once, when it starts loading the module')
}
}
What am I doing wrong and how can I pass custom ssr data to the client side renderer?
Ok, just found the solution to the core problem of passing custom data from the (ssr) server to the client:
Create a plugin: plugins/my-plugin.js
export default ({ beforeNuxtRender, nuxtState }) => {
if (process.server) {
beforeNuxtRender(({ nuxtState }) => {
nuxtState.myCustomData = true
})
} else {
console.log('My cystom data on the client side:', nuxtState.myCustomData)
}
}
Then register the plugin in your nuxt.config.js:
module.exports = {
plugins: ['~/plugins/my-plugin']
}
Docs here.
I have a login modal that I activate by setting .is-active to it. For this, I have a method like this:
methods: {
toggleModal: function (event) {
this.isActive = !this.isActive
}
}
that I run onclick. Depending on the boolean value of isActive, my modal gets the class .is-active.
Thing is, in my modal I have a button that takes the user to a new view which means it's rendering a new component, with this code:
<router-link class="control" #click="toggleModal()" to="/register">
As you can see, it's routing to /register. Before doing this, I need to run toggleModal() so that the modal gets closed. Right now it's routing without running the method which means that the new view has my modal overlay which is... not optimal.
Is there any good way to do this in Vue? Could I maybe create a method, that first calls toggleModal(), and then routes from the method?
Thanks.
I would define a method that calls toggleModal first, then navigates. Like so:
methods: {
navigateAway () {
this.isActive = !this.isActive
this.$router.push('/register')
}
}
You don't need the event argument unless you intend on capturing more data from the event or event target. You could also wrap the router push in a setTimeout if you so desire, for perhaps cleaner looking view changes.
methods: {
navigateAway () {
let vm = this
vm.isActive = !vm.isActive
setTimeout(function () {
vm.$router.push('/register')
}, 50)
}
}
Of course, there are hooks that you can use from vue-router that make this easy. Example (assuming you're using single file components and Vue.js 2.x):
export default {
data () {
return {
isActive: false
}
},
beforeRouteLeave (to, from, next) {
this.isActive = false // I assume that you would not want to leave it open upon navigating away
next()
}
}
Link to vue router hooks: https://router.vuejs.org/en/advanced/navigation-guards.html
Vue - I want to track user changes on a page and send those updates if they navigate away. The basic idea is
//child
beforeDestroy: function() {
var that = this;
axios.post('gate/cart.php', userUpdates)
.then(function(res) {
if (res.data.success) {
that.$emit('updateCart', res.data.cart);
//parent (App.vue)
<router-view
#updateCart="updateCart"
...
methods: {
updateCart: function(newCart) {
alert('caught');
this.cart = newCart;
The dev tools show me the emit is emitted and the correct payload (res.data.cart) is sent, but the parent method isn't called. (That alert doesn't trigger.) I know the updateCart method in the parent is working, as another component uses it fine like this with a regular method:
addToCart: function() {
var that = this;
axios.post('gate/cart.php', this.dataToSend)
.then(function(res) {
if(res.data.success === true) {
that.$emit('updateCart', res.data.cart)
that.$router.push({ path: '/product/' + that.product.id})
}
If the ajax is working, I get a correct $emit, and the target method is ok, what lifecycle hook caveat is stopping me from executing the parent method? Do you know a better way to do this? (I want to check the success of the ajax call before updating the parent data.)
In the example below I use created lifecycle to subscribe to event service. Is it a normal practice? Is there a more appropriate way or lifecycle method to do this kind of stuff?
const ViewComponent = {
data(){
return {
pathname: window.location.pathname
}
},
created(){
eventService.on('routeResolved', (route) => {
this.pathname = route.pathname
})
},
computed: {
component () {
return routes[this.pathname]
}
},
render (h) {
return h(this.component)
}
}
Which lifecycle method you use for initialization depends entirely on what you need access to. If you need to manipulate the DOM in any way, you cannot do that until the mounted lifecycle event. For setting up an event handler like you are in the question, using the created lifecycle event is perfectly fine.
Mainly for one-time initialization actions, you will choose either created or mounted. If you need something done every time the component receives new properties you might use beforeUpdated or updated.
Take a look at the documentation for a full description.