Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
990 views
in Technique[技术] by (71.8m points)

vuejs2 - Vue: Setting Data by matching route query

I'm attempting to set data fields provided by an array based on the Vue Router query. For example, when someone lands on my website using example.com/?location=texas, I want to set the location data by an array.

An example the array:

locations {
    {
        slug: "texas",
        tagline: "Welcome to Texas",
    }, {
        slug: "california",
        tagline: "Welcome to California",
    }
}

I know this should be done using a computed property, however I am unable to get anything functioning. I've tried simple tests like if (this.slug.location === "texas"), and I cannot get the location data to populate. I would also like to provide default data in case there are no route matches.

Any help is extremely appreciated!

Edit:

I can accomplish this in a very manual way. Right now, I'm setting the query in data by the following:

slug: this.$route.query.location

I can display specific text by doing something like:

h3(v-if="slug === 'texas'") This will show for texas
h3(v-else-if="slug === 'california'") This will show for California
h3(v-else) This is default

The issue with this approach is there are various elements I need to customize depending on the slug. Is there any way I can create an array, and move whichever array matches a key in an array to the data??

question from:https://stackoverflow.com/questions/65848454/vue-setting-data-by-matching-route-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be able to access a query param using the following (link to Vue Router documentation):

this.$route.query.location

So based on what you listed I would do something like...

export default {
  computed: {
    displayBasedOnLocationQueryParam() {
      switch(this.$route.query.location) {
        case 'texas':
          return 'Welcome to Texas'
        default:
          return 'hello there, generic person'
      }
    }
  }
}

Note that I'm not using your array explicitly there. The switch statement can be the sole source of that logic, if need be.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...