L
L
litash2018-06-26 15:31:13
Vue.js
litash, 2018-06-26 15:31:13

How to make Vue.js understand jQuery, JS when switching between components?

Sorry for the wording of the question. I learn Vue.js and I don’t understand JS myself). There is a training project that I'm quietly doing, in general, the problem is this. There are components and switching between them, if I insert a button into the component and write jQuery code to change the text in it (for example), then when I switch to the second component and back, the button no longer works. As I understand it, when switching between components, Vue draws this component again, but the script for the content inside it no longer sees. I tried keep-alive but it doesn't help. The option without components using only v-show is not suitable. How to make Vue understand pure js and left libraries even when switching between them? I googled and tried to insert the mounted jQuery code into the mounted jQuery but there was no result. Can you please explain why or not to use Vue for this at all?
Switching is implemented with the
component(
v-if="selected"
v-bind:is="selected"
)
template tag and an array with data.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Askhat Bikmetov, 2018-06-26
@litash

The fact is that when it selectedreturns false, the element is removed from the DOM tree and, therefore, the jquery plugin initialized on it stops working. To avoid this, you need to learn to understand the lifecycle of a Vue component. In addition, code that works with the DOM but is not an integral part of the component should be separated into directives. For example (for single-file components):

<template>
  <div v-fancy-plugin="{ argumentObjectKey: 'value' }"></div>
</template>
<script>
import $ from 'jquery'
import fancyPlugin from 'fancy-plugin'

export default {
  directives: {
    fancyPlugin: {
      inserted (element, argumentObject) {
        $(element).fancyPluginInit(argumentObject)
      }
    }
}
</script>

This way the jquery code will be initialized the moment the element is placed in the DOM tree.

A
Anton Anton, 2018-06-26
@Fragster

Throw away jq.
There are practically no tasks that jquery solves that vuejs does not solve in the same or less code. An exception may be any ready-made components such as calendars, but it’s not so difficult to draw / find them ready for vue.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question