How do I retrieve a variable from .js file? - javascript

How do I access a variable defined in a js file from a vue file? Is there a way to pass this variable to the vue file? In the code below, I've got a template.js file and a contact.vue file. I am converting mjml to html in the template file and I need to access the output saved to the plainHmtl variable from the vue file.
template.js
const mjml2html = require('mjml')
const Vue = require('vue')
const app = new Vue({
data: {
name: ''
},
template: `
<mj-section>
<mj-column>
<mj-text font-size="20px" color="#F45E43" font-family="helvetica">Hello {{ name }}</mj-text>
</mj-column>
</mj-section>`
})
const renderer = require('vue-server-renderer').createRenderer({
template: `
<mjml>
<mj-body>
<!--vue-ssr-outlet-->
</mj-body>
</mjml>`
})
renderer.renderToString(app).then(html => {
const htmlWithoutDataServerRenderedAttribute = html.replace(`data-server-rendered="true"`, '')
const plainHtml = mjml2html(htmlWithoutDataServerRenderedAttribute)
console.log(plainHtml.html)
})
contact.vue
<template>
<div class="sign_up" id="signupform">
<main role="main">
<div class="SignUp_container">
<form class="form-signup" #submit.prevent="processForm">
<input type="text" name="name" placeholder="Enter First Name" required/>
<input type="text" name="lname" placeholder="Enter Last Name" required/>
<input type="email" name="mailaddr" placeholder="Your email address" required/>
<div class="sign_cancel_buttons">
<router-link to="/">
<button id="canlbtn" type="cancel" class="clbtn">
Cancel
</button>
</router-link>
<button id="signupbtn" type="submit" name="sendmsg-button" class="signbtn">
Sign Up
</button>
</div>
</form>
</div>
</main>
</div>
</template>
<script>
export default {
methods: {
// how do I access plainHtml here?
}
}
</script>

In template.js, define a variable where you will have the final result of converting your html, once defined just add this to the end of the file:
export { varHTML }
Now in contact.vue you have to import and use the export we made from template.js, consider that you must modify the import path according to the case that you are handling for your files:
import { varHTML } from './template.js'
<script>
export default {
data() {
return {
plainHtml: null
}
}
methods: {
// how do I access plainHtml here?
// any method that is going to be needed now will have plainHtml available
},
created () {
this.plainHtml = varHTML
}
}
</script>

Related

vue 3 composition multiple input with same ref or retrieve all input containing the same text

I have a component named InputWithValidation that
I inserted in a form with some other components and I'm trying to get all instance to check if they are all valid at once.
With one InputVithValidation I would have check if it's valid this way:
<script setup>
import { ref } from 'vue'
const inputEmail = ref(null);
function submit(){
if(inputEmail.isValid()){
//call API
}
}
</script>
<template>
<form>
<InputWithValidation ref="inputEmail" type="email" validationType="EMAIL"/>
<button #click="submit">Submit</button>
</form>
</template>
But I actually have multiple InputWithValidation in my form:
<template>
<form>
<InputWithValidation ref="inputEmail" type="email" validationType="EMAIL"/>
<InputWithValidation ref="inputFirstName" type="text" validationType="TEXT"/>
<InputWithValidation ref="inputEmail" type="text" validationType="TEXT"/>
<!-- ... -->
<button #click="submit">Submit</button>
</form>
</template>
And I wish to avoid this:
<script setup>
import { ref } from 'vue'
const inputEmail = ref(null);
const inputFirstName = ref(null);
const inputEmail = ref(null);
//....
</script>
I tried to replicate the $refs array of the option API or the comportment with a ref in a v-for list by setting the same ref to all my components and get it as array:
<script setup>
import { ref } from 'vue'
const inputs = ref([]);
function submit(){
if(inputs.find(input => !input.isValid()) == null){
//call API
}
}
</script>
<template>
<form>
<InputWithValidation ref="inputs" type="email" validationType="EMAIL"/>
<InputWithValidation ref="inputs" type="text" validationType="TEXT"/>
<InputWithValidation ref="inputs" type="text" validationType="TEXT"/>
<button #click="submit">Submit</button>
</form>
</template>
But it's not working.
Is there anyway to retrieve all refsat once ?

What should i use to access the data in different .JS file from a .JS file

Hello I am working on a project where i need to access the json response results into another .js files.
In this code i am getting json data in result variable in function handleLogin. How could i export this variable and import/call in different .js file to use the data of result variable. I cannot export this function handLogin cause its been called onSubmit in html code.
Like this result JSON data contains some data like name age and various other parameters and i want it to display it in a different .js file how could i do that. How could i retrieve this variable.
import React from "react";
import axios from "axios";
class Login extends React.Component{
render(){
return (
<div className="container">
<div className="row ces-login-bg">
<div className="col-md-12 col-lg-6 login-intro-container">
<img alt = "" className="ces-logo" src="https://www.cesltd.com/img/ces-logo.png"/>
<h1 className="timesheet-head">Timesheets</h1>
<p className="intro-text">a comprehensive solution for your timesheets, holidays and leaves</p>
</div>
<div className="col-md-12 col-lg-6 ">
<form className="form-container" onSubmit={handleLogin}>
<h1 className="login-heading">Login</h1>
<div className="email-label ">
<label className="label-element">Email</label>
<input className="input-element" type ="email" id = 'email' name="email" required/>
</div>
<div className="password-label ">
<label className="label-element">Password</label>
<input className="input-element" type="password" id = "password" name="password" required/>
</div>
{/* <p className="error-message">Invalid login credentials</p> */}
<button type ="submit" className="button-container" >
<p className="login-button">Login</p>
{/* <i className="fa-solid fa-chevron-right"></i> */}
</button>
</form>
</div>
</div>
</div>
)
}
}
async function handleLogin(event){
event.preventDefault();
let payload = {
"params":{"db":"dev02","login":event.target.email.value, "password":event.target.password.value}
}
let result = await axios.post('http://dev02.abcltd.net:8020/mobile/session/authenticate', payload);
try{
if (result.data.result.message.toLowerCase() === 'success') {
window.open('/Timesheets','_self');
}
}
catch{
alert('Invalid Email or Password')
}
}
export default Login
Expecting to export this result data and import it in different .js file

Why is class JS is executing twice?

In general, the problem is this. I create a class, write output to the console, and output the code twice. What to do?
import { CoreValid } from "./core.component"
export class Validator extends CoreValid {
constructor(elementId, btn, dataName) {
super(btn)
this.$dataName = dataName
this.$el = document.querySelector(elementId)
}
init() {
this.$btn.addEventListener('click', this.haha.bind(this))
}
haha(event) {
event.preventDefault()
console.log('one')
}
}
And its main component
export class CoreValid {
constructor(btn) {
this.$btn = document.querySelector(btn)
this.init()
this.idCreate()
}
init() {}
idCreate(){}
}
And this is screen
enter image description here
And this is HTML
<form action="">
<input type="text" class="main-input" placeholder="Title" data-nav="title" id="1" name="">
<div class="block-colors">
<input type="text" data-nav="color" placeholder="RGB" id="2">
</div>
<button class="submit">Submit</button>
</form>

How can I display required html 5 in vue component?

My vue component like this :
<template>
<div>
...
<form class="form-horizontal" id="form-profile">
...
<input type="number" class="form-control" required>
...
<button type="submit" class="btn btn-primary" #click="submit">Submit</button>
...
</form>
...
</div>
</template>
<script>
export default {
...
methods: {
submit(e) {
e.preventDefault()
if (this.checkForm()) {
// do ajax here
}
},
checkForm() {
let field = true
$('#form-profile :required').each(function(i) {
if(this.checkValidity() == false)
field = false
})
return field
},
}
}
</script>
I using required html5 to validation
I using e.preventDefault() to prevent page redirects. Because I want to using ajax
My problem here is the required validation html5 not show if not filled. Maybe it because I using e.preventDefault()
How can I display the required html5?
In order to work as expected you have to set the v-on:submit method on the form tag, and have a button/input type "submit".
Also, notice the event modifier prevent on the #submit, it's a shorcut to not have to write e.preventDefault() on the method
new Vue({
el: '#app',
data() {
return {
myText: ''
}
},
methods: {
submitForm() {
alert('submited: ' + this.myText)
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
<div id="app">
<form #submit.prevent="submitForm">
<input type="text" v-model="myText" required />
<button type="submit">Submit</button>
</form>
</div>

Reset form state VueJS and VueRouter

I am currently working on a step by step registration created with VueJS and VueRouter.
The basic premise of the form is that a user has to select a signup option before proceeding to enter his personal details. However, I would like the form to be reset every time a different sign up option is selected.
VueJs + VueRouter Multi Step Form
/**
*
* #type {Vue}
*/
let page2Component = Vue.component('pageTwo', {
data: function() {
return {
step1: {
firstname: '',
lastname: ''
}
}
},
template: `<div>
<h2>Registration</h2>
<form action="" method="post" role="form">
<legend>Details</legend>
<div class="form-group">
<label for="firstname">First name</label>
<input type="text" class="form-control" name="firstname" id="firstname" placeholder="First name..." v-model.trim="step1.firstname">
</div>
<div class="form-group">
<label for="lastname">Last name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last name..." v-model.trim="step1.lastname">
</div>
</form>
<div>
<router-link to="/" class="btn btn-default">Back</router-link>
<router-link to="/" class="btn btn-primary">Next Page</router-link>
</div>
</div>`,
created: function () {
},
methods: {
resetUserDetails: function() {
this.step1.firstname = '';
this.step1.lastname = '';
}
}
});
/**
*
* #type {Vue}
*/
let page1Component = Vue.component('pageOne', {
data: function() {
return {
selectedSignUpOption: ''
}
},
template: `<div>
<h2>Registration</h2>
<form action="" method="post" role="form">
<legend>Sign Up Options</legend>
<div class="form-group">
<div>
<div class="radio">
<label>
<input type="radio" name="signup_option" value="user" v-model.trim="selectedSignUpOption"> Register As A User
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="signup_option" value="content-editor" v-model.trim="selectedSignUpOption"> Register As A Content Editor
</label>
</div>
</div>
</div>
</form>
<div>
<router-link to="/page2" class="btn btn-primary" v-bind:disabled="!signupOptionSelected">Next Page</router-link>
</div>
</div>`,
created: function () {
},
watch: {
'$route'(to, from) {
// react to route changes...
// don't forget to call next()
console.log('to: ', to);
console.log('from: ', from);
console.log(this);
},
selectedSignUpOption: function() {
console.log(this);
console.log(this.selectedSignUpOption);
}
},
computed: {
signupOptionSelected: function() {
return this.selectedSignUpOption !== '';
}
}
});
/**
*
* #type {Vue}
*/
let wizardComponent = Vue.component('wizardForm', {
template: `<div>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>`,
created: function () {
let children = [];
children.push({path: '/', component: page1Component});
children.push({path: '/page2', component: page2Component});
router.addRoutes(children);
}
});
/**
* Vue App Initialisation
*/
Vue.config.devtools = true;
Vue.use(VeeValidate);
const routes = [];
const router = new VueRouter({
routes // short for routes: routes
});
console.log('routes', routes);
document.addEventListener('DOMContentLoaded', function () {
/**
*
*/
let vm = new Vue({
el: '#app',
router,
});
});
I have included a link to the form that I am working on. Any one have any idea as to how I can achieve this? Ideally, I would like to be able to call the resetUserDetails method in the page2Component when the sign up option is different to the last one that was selected.
Any suggestions would be appreciated. I am using VueJS 2 btw.
Thanks,
Emmanuel
For this to work you should pass selected value as to second component.
your route config will look like this
children.push({path: '/:option/page2', component: page2Component});
form component
watch: {
'$route.params.option'(to, from) {
if((this.prevSelection && this.$route.params.option) && (this.$route.params.option !== this.prevSelection)){
this.prevSelection = this.$route.params.option
this.resetUserDetails()
}
}
}
For more information please have a look at this

Categories