I have an app with plain JS and Vue in one file. I need to pass a variable value from JS to Vue. 0. All code in one file:
<script>
plain js
var plainJS = 100;
</script>
<script>
var app = new Vue({
el: '#vue-app',
....
</script>
main functionality of the app is on plain js. Vue does a small part with UI.
with js I can catch if one of my elements changed position (a dot on the screen)
I need fire popup(some alert) if checkBox is selected but the Dot wasn't moved.
checkBox is a Vue element
I can pass data from Django to Vue
this.vueVar = {{ djangoVar|safe }}
So how to pass
*var plainJS = 100;*
to vue app from plain JS part of the code?
Can you give me a simple way to set vueVar = plainJS?
This is one of the ways you can send data from js to js file. In your mainJS function popup you create a receive function that listens for change on storge.
$(window).on('storage', event => this.message_receive(this)(event));
message_receive(self) {
return function insideFun(ev) {
if (ev.originalEvent.key !== 'checkboxFromVue') return;
var message = JSON.parse(ev.originalEvent.newValue);
if (!message) return;
// Handle acction when checkbox is clicked
};
}
And in your Vue you use localstorage set item with key "checkboxFromVue"
localStorage.setItem('checkboxFromVue', valueOfCheckBox));
What this will do is whenever your checkbox changes localstorge value your main js known and receive that value
You can access a ref on the root component if you store a variable of what createApp returns. Then each time you would update your plainJS var, also reassign a matching property (ref) on the "app" object. For the initial value you may use a "root prop" which is the 2nd param of the createApp function.
main.js
import { createApp } from "vue";
import App from "./App.vue";
var plainJS = 100;
const myApp = createApp(App, { plainJS: plainJS }).mount("#app");
setInterval(() => {
//interval used here to simulate a value that changes at arbitrary times
plainJS++;
myApp.varFromOutsideVue = plainJS; // 👀 this updates the ref
}, 500);
App.vue
<template>
<h1>{{ varFromOutsideVue }}</h1>
</template>
<script>
import { onMounted, onUnmounted, ref } from "vue";
export default {
name: "App",
props: {
plainJS: { type: Number },
},
setup(props) {
const varFromOutsideVue = ref(props.plainJS);
return {
varFromOutsideVue,
};
},
};
</script>
https://codesandbox.io/s/eager-rubin-6fv7p7?file=/src/main.js