0
votes

I have a landing page, inside I use a v-for to iterate 3 option divs, each div receives their corresponding props from the landing component, one prop I pass is a name prop, when you click on the selected div it emits an event with that property and also redirects to a main component which gets populated depending on the name.

//option div
export default {
  props:['name'],
  data(){
    return {

      }
    }
  },
 methods: {
   selectName() {
     let name = this.name
     this.$eventHub.$emit("select-name", name);
   }

And in the main component I listen to the event on mount and I use that info in the title of the component:

mounted: function() { 
  this.$eventHub.$on("select-name", name => { 
    this.$store.dispatch("information/getInfoByName", name); 
    this.title = name
} })

I want to add a validation, if the user goes directly to https://example.com/main without selecting a option div first then I want it to return to the landing page:

data() {
 name: null
},
computed:{
  nameValidation(){
    if(this.name == null) {
     swal({
     text: "Please select a name first",
     icon: "warning",
     buttons: false,
     timer: 1500
     });

     setTimeout(function () {
       document.location.href = '/landing'
     }, 1500);
   }

It works... when I have the Vue devtools open, but when I close it, it doesn't work. It's somehow executing the computed property. I tried using it as a method and calling it in the title of my page <h1>{{nameValidation}}<h1> but it always checks this.name as null even if you choose an option, I'm guessing it has to do with the dispatch that I do on the mount of the main component, my questions is why is the computed only working with devtools open?

1
Are you using Vue Router?Andrew Vasilchuk
Yes, both landing and main are different paths.ahzep
How are you passing name to the main page?Andrew Vasilchuk
with vuex ...mapGetters({ getClusterInfo: "getClusterInfo/getClusterInfo" }),ahzep
Can you please provide the code that sets the name property in your data? The code above makes it look as if name is simply never changed to any value. (Another issue is that you should indeed not handle this logic in a computed property but in a lifecycle hook)MarcRo

1 Answers

1
votes

Try to do it in the mounted hook of page component, like this:

...
props: {
  name: {
    type: String,
    required: true
  }
},
mounted() {
  if (this.name == null) {
    swal({
      text: 'Please select a name first',
      icon: 'warning',
      buttons: false,
      timer: 1500,
    })

    setTimeout(() => {
      document.location.href = '/landing'
      // this.$router.push('/landing') // uncomment if you are using Vue Router
    }, 1500)
  }
},
...