Reputation: 763
I have a Vue component that has a 'select state' dropdown element. I want to add a js function that populates the options with the 50 states instead of having to hard code them. I will also have this dropdown in a couple other places so I want this function to be accessed from outside the component. What is the best way to accomplish this?
<template>
<div class="section" v-bind:class="sectionClass" data-mh="group3">
<h3>{{sectionTitle}}</h3>
<div class="section-content display-area">
<i class="icon icon-health img-left"></i>
<form>
<div class="row mt">
<div class="col-xs-12 col-sm-8">
<div class="same-height-parent">
<div class="same-height">
<input type="text" class="form-control" placeholder="Enter Name">
</div>
<div class="same-height">
<select name="state" id="state" class="form-control" tabindex="9">
<option value="">- Select State -</option>
</select>
</div>
</div>
<!-- same-height-parent -->
</div>
<div class="col-xs-12 col-sm-4">
<button type="submit" class="btn btn-success btn-block btn-fz20">Search</button>
</div>
</div>
</form>
</div>
</div>
</template>
<script>
export default {
name: 'nameSearch',
data: function() {
return {
sectionTitle: 'Name Search'=
}
}
}
</script>
Upvotes: 3
Views: 4923
Reputation: 8506
you may want to export the function from some other file, this is simply a case of declaring it the way you want.
in some other file...
// utils.js
export function createOptions (someArg) {
let options = [ ... ]
return options
}
in your .vue file
<script>
import { createOptions } from './utils'
export default {
...
data () {
return {
options: createOptions()
}
}
}
</script>
You may also want to try snovakovic's advice to externalise the dropdown component instead, whatever brings you more flexibility
Upvotes: 5
Reputation: 314
Why not just create states components that handles drop-down and then include that component everywhere where it's used.
If you want just a function then create js file that expose that function and than import that file inside component.
Upvotes: 0