I have a child component called ZimModel.vue
where I created a method drawGrid()
. I need to call this method in parent component (mainPage.vue
). The idea is to call this method once the user has finished typing values in input (namely: width of the grid - I added @input
event to v-model="inputWidth"
). That's why I also use setTimeout
with 5 sec delay. However, I have no idea how to 'send' this method up to parent component. I tried with emit
but I don't think it makes any sense.
I use Vuex store in my app but this particular method is strictly related to other data and methods in ZimModel.vue
so I don't think it' makes sense to move it to Vuex. Is there any pattern/good practice I should follow in this case?
Here is a reproducible example: https://codesandbox.io/s/vue-2-playground-vuex-drag-and-snap-to-tiles-un6984?file=/src/components/mainPage.vue.
As an example I added myGreeting()
method (in mainPage.vue
) to show how I want my program to work. I need to replace this exemplary method with target drawGrid()
method.
CodePudding user response:
Using $ref will solve your issue:
<ZimModel ref="zimModel" />
And inside your method:
triggerDrawing() {
clearTimeout(this.timer);
// this.timer = setTimeout(this.myGreeting, 5000);
this.$refs.zimModel.drawGrid();
}
CodePudding user response:
Whilst the using ref
should work, you should consider outsourcing the method to a .js and importing the method in the files you need it. This is especially recommended when using a method in several components.
In the new file:
export function drawGrid() {
// Your code
}
In your components
</template>
<script>
import { drawGrid } from 'relativePath'
// using {} you can import a single function or few select to improve effectiveness
...
Then you can just call the function.