why the el-input could not input anything in google chrome extension - javascript

Now I am writing a Google Chrome Extension that using vue el-input to input the username and password, when input username and password, store the username and password into storage.the code like this:
<template>
<div class="login">
<div class="title">Login</div>
<div class="setting-name">username:</div>
<div class="setting-input">
<el-input #change="saveConfig" placeholder="please input username" ></el-input>
</div>
<div class="setting-name">password:</div>
<div class="setting-input">
<el-input #change="saveConfig" placeholder="please input password"></el-input>
</div>
</div>
</template>
but when I type the username and password in the UI, the el-input did not show what I am inputting. It means could not input anything. what should I do to fix it? The vue version is:
"vue": "2.6.12",
"vue-loader": "15.9.5",
"vue-template-compiler": "2.6.12",
I have tried to forceUpdate like this:
<el-input #change="saveConfig" placeholder="please input username" #input="onInput()"></el-input>
methods: {
onInput(){
this.$forceUpdate();
},
}
still not work. This is my full code:
<template>
<div class="login">
<div class="title">登录</div>
<div class="setting-name">用户名:</div>
<div class="setting-input">
<el-input #change="saveConfig" placeholder="请输入你的用户名" #input="onInput()"></el-input>
</div>
<div class="setting-name">密码:</div>
<div class="setting-input">
<el-input #change="saveConfig" placeholder="请输入你的密码"></el-input>
</div>
</div>
</template>
<script>
export default {
name: 'Login',
data: () => ({
loading: true,
defaultConfig,
config: defaultConfig,
time: '',
leftTime: '',
second: 0,
refreshDisabled: false,
isChrome: navigator.userAgent.indexOf('Chrome') !== -1,
}),
methods: {
onInput(){
this.$forceUpdate();
},
saveConfig() {
saveConfig(this.config, () => {
this.$message({
message: '保存成功',
type: 'success'
});
});
},
toHotkey() {
chrome.tabs.create({
url: 'chrome://extensions/shortcuts'
});
},
refreshRu() {
this.refreshDisabled = true;
refreshRules(() => {
this.second = 0;
this.time = secondToTime(this.second);
this.leftTime = secondToTime(this.config.refreshTimeout - this.second);
this.refreshDisabled = false;
});
},
refreshTime() {
getRulesDate((date) => {
this.second = (+new Date - +date) / 1000;
this.time = secondToTime(this.second);
this.leftTime = secondToTime(this.config.refreshTimeout - this.second);
setTimeout(() => {
this.refreshTime();
}, 1000);
});
}
}
}
</script>

Related

creating custom error when no entries has been made using toast for React

I am in the middle of creating error handlings using toast function for my react app signin and register pages, I was able to successfully create a toast function that when logging in with wrong email or password they should receive an error message.
however, I am trying to accomplish the same thing with a different error message when the user clicks on sign in without entering any information, but I can't get it to work, when I click on the login without entering anything it gives me the same error messgae as i set up when entering wrong credentials.
what am I missing?
please help me
from signin.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
class Signin extends React.Component {
constructor(props) {
super(props);
this.state = {
signInEmail: "",
signInPassword: "",
};
}
showToast = () => {
toast.error("invalid username or password", {
position: "top-right",
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
};
showToast1 = () => {
toast.error("invalid username or password", {
position: "top-right",
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
};
onEmailChange = (event) => {
this.setState({ signInEmail: event.target.value });
};
onPasswordChange = (event) => {
this.setState({ signInPassword: event.target.value });
};
onSubmitSignIn = (event) => {
event.preventDefault();
let regex = /^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+#[A-Za-z0-9.-]+$/g;
const isEmailValid = this.state.signInEmail.match(regex);
const signInEmail = this.state.signInEmail
const signInPassword = this.state.signInPassword
if (!isEmailValid) {
return this.showToast();
} else if(!signInEmail || !signInPassword) {
return this.showToast1()
}
fetch("https://ancient-sea-46547.herokuapp.com/signin", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword,
}),
})
.then((response) => {
if (!response.ok) throw new Error("invalid");
return response.json();
})
.then((user) => {
if (user.id) {
this.props.loadUser(user);
this.props.onRouteChange("home");
}
})
.catch((error) => this.showToast(), this.showToast1);
};
render() {
const { onRouteChange } = this.props;
return (
<article className="br3 ba b--black-10 mv4 w-100 w-50-m w-25-l mw6 shadow-5 center">
<ToastContainer />
<main className="pa4 black-80">
<form className="measure">
<fieldset id="sign_up" className="ba b--transparent ph0 mh0">
<legend className="f1 fw6 ph0 mh0">Sign In</legend>
<div className="mt3">
<label className="db fw6 lh-copy f6" htmlFor="email-address">
Email
</label>
<input
className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="email"
name="email-address"
id="email-address"
onChange={this.onEmailChange}
/>
</div>
<div className="mv3">
<label className="db fw6 lh-copy f6" htmlFor="password">
Password
</label>
<input
className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="password"
name="password"
id="password"
onChange={this.onPasswordChange}
/>
</div>
</fieldset>
<div className="">
<input
onClick={this.onSubmitSignIn}
className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
type="submit"
value="Sign in"
/>
</div>
<div className="lh-copy mt3">
<p
onClick={() => onRouteChange("register")}
className="f6 link dim black db pointer"
>
Register
</p>
</div>
</form>
</main>
</article>
);
}
}
export default Signin;

Refresh data table event after file upload

I am beginner web developer. I make my first project in Vue.
I make form with files upload in vue 2 and laravel.
My full code:
View: https://pastebin.com/QFrBfF74
Data table user file: https://pastebin.com/sGQH71XZ
This code work fine, nut I have small problem with reload ata-table-user-files after files upload.
Modal where I have file uploader:
<div>
<CModal
title="Dodaj plik"
color="info"
:show.sync="filesModal"
size="xl"
:closeOnBackdrop=true
:centered="true"
>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dodaj plik w formacie: jpg, jpeg, png, bmp, pdf, xml, csv, doc, docx,
txt, rtf
</div>
<div class="card-body">
<CRow>
<CCol md="12">
<CSelect id="dispatcher_id"
label="Wybierz kategorię pliku"
v-model.trim="$v.form.file_category.$model"
:options="filesCategory"
>
</CSelect>
</CCol>
<CCol md="12">
<CTextarea
label="Opis pliku"
placeholder="Wpisz opis dodawanego pliku"
rows="9"
v-model.trim="$v.form.file_content.$model"
/>
</CCol>
</CRow>
<form enctype="multipart/form-data" #submit="formFileSubmit">
<input type="file" class="form-control" v-on:change="onFileChange" name="file_name" ref="inputFile">
<button class="btn btn-primary btn-block">Dodaj plik</button>
</form>
</div>
</div>
</div>
</div>
</div>
</CModal>
</div>
Refresh action I need after "Sukces Plik dodany poprawnie!" I need reload files list:
<data-table-user-files
:fetch-url="datatTableUrl5"
:columns="['id', 'description', 'file_category','user_id' ]"
:headers="{'id': 'ID','description': 'Opis','file_category': 'Kategoria','user_id': 'Twórca'}"
:routeName="routeAddName5"
></data-table-user-files>
I try do this in function:
getFilesList()
{
let self = this;
axios.get(this.$apiAdress + '/api/tasks-file-list?token=' + localStorage.getItem("api_token") + '&taskId=' + self.form.taskId)
.then(function (response) {
self.addedFiles = [];
self.addedFiles = response.data
}).catch(function (error) {
console.log(error);
self.$router.push({path: '/login'});
});
},
But it's not working :(
How can I repair it?
Please help me.
Changing the URL in order to trigger re-fetching of the data:
<template>
<data-table-user-files
:fetch-url="datatTableUrl5"
:columns="['id', 'description', 'file_category','user_id' ]"
:headers="{'id': 'ID','description': 'Opis','file_category': 'Kategoria','user_id': 'Twórca'}"
:routeName="routeAddName5"
/>
<script>
export default
{
data()
{
return {
triggerRefetch: 0,
};
},
computed:
{
datatTableUrl5()
{
return `https://my.api.example.com/api/endpoint?t=${triggerRefetch}`;
},
},
methods:
{
filesSuccessfullyUploaded()
{
this.triggerRefetch++;
},
}
}
</script>
import Axios from 'axios';
export default
{
props:
{
fetchUrl:
{
type: String,
required: true
},
},
data()
{
files: [],
},
watch:
{
fetchUrl:
{
immediate: true,
handler()
{
this.getFilesList();
}
}
},
methods:
{
getFilesList()
{
Axios.get(this.fetchUrl).then(response => this.files = response.data || []);
}
}
}

How can I use vue validation with Jest?

I'm writing a unit test with vue 3 using vee-validate 4 and Jest. But I'm new to this and I'm stuck at one place.
I have a TextInput component that I use validations, and when I call this component, I do validation when submit is done.
There is a separate component where I write the form where I use these textInputs.
First let me show you the code in my TkTextInput component.
<template>
<div
class="tk-Input"
:class="{ 'has-error': !!errorMessage, success: meta.valid }"
>
<label class="tk-label" :for="name">{{ label }}</label>
<input
id="demos"
class="col-12"
v-model="inputValue"
:name="name"
:type="type"
:value="inputValue"
:placeholder="placeholder"
#input="handleChange"
#blur="handleBlur"
v-bind="$attrs"
/>
<p class="help-message" v-show="errorMessage || meta.valid">
{{ errorMessage }}
</p>
</div>
</template>
<script>
import {useField} from "vee-validate";
import {watch} from "vue";
export default {
props: {
type: {
type: String,
default: "text",
},
modelValue: String,
value: {
type: String,
default: "",
},
name: {
type: String,
required: true,
},
label: {
type: String,
},
placeholder: {
type: String,
default: "",
},
},
emits: ['update:modelValue'],
setup(props, {emit}) {
const {
value: inputValue,
errorMessage,
handleBlur,
handleChange,
meta,
} = useField(props.name, undefined, {
initialValue: props.value,
});
watch(inputValue, (val) => {
emit('update:modelValue', val);
});
watch(() => props.modelValue, (val) => {
if (val !== inputValue.value) {
inputValue.value = val;
}
})
return {
handleChange,
handleBlur,
errorMessage,
meta,
inputValue,
};
},
};
</script>
Then in my form component where I call these textInputs is as follows.
<Form
#submit="onSubmit"
:validation-schema="schema">
<div class="grid ">
<div class="col-12 lg:col-6 lg:mb-0">
<tk-text-input v-model.trim="vehicleInfo.Plate" label="Plaka*" name="Plate" type="text"/>
</div>
<div class="grid ">
<div class="col-12 lg:col-6 lg:mb-0">
<tk-text-input v-model.trim="vehicleInfo.PhoneNumber" label="Cep Telefonu*" name="PhoneNumber"/>
</div>
<div class="col-12 lg:col-6 lg:mb-0">
</div>
</div>
<Button #click="clicked" class=" p-button-success" type="submit">{{buttonLabel}}</Button>
</Form>
Now I want to test the validation process in the TkTextInput component when the button clicks when I click the button in the component where I wrote the form with gesture. But I couldn't do it.
The test I wrote in the .spec file is as follows.
describe('TkTextInput.vue', () => {
it('when validation is done', async() => {
const wrapperVehicle = mount(VehicleInfoDialog, {
global:{
plugins: [PrimeVue]
},
})
const button = wrapperVehicle.find("button")
button.trigger('submit')
await button.trigger("click")
expect(wrapperVehicle.html()).toContain("Boş Geçilemez.")
});
})

How to share #focus="focus('')" and #blur="blur('')"?

How to share #focus="focus('')" and #blur="blur('')"?
If the email input format is correct, but the name input format is wrong, the name will not display an error message. I am thinking about how to use the "fieldName" so that he can judge which I clicked.
If there are many regular expressions that need to be judged, is there a way to share function?
const app = new Vue({
el: "#app",
data: {
carrierEmailError: false,
carrierNameError: false,
carrierEmailErrMsg: '',
carrierNameErrMsg: '',
},
methods: {
// emailRule
emailRule() {
var isEmail = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/
if (!isEmail.test(this.carrierEmail)) {
return false
}
return true
},
// nameRule
nameRule() {
var isText = /^[A-Za-z0-9]{1,10}$/
if (!isText.test(this.carrierName)) {
return false
}
return true
},
focus(fieldName) {
this.carrierEmailError = false;
this.carrierNameError = false;
},
blur(fieldName) {
if (this.emailRule() === true) {
this.carrierEmailError = false;
this.carrierEmailErrMsg = '';
return
} else {
this.carrierEmailError = true;
this.carrierEmailErrMsg = 'Incorrect email format';
}
if (this.nameRule() === true) {
this.carrierNameError = false;
this.carrierNameErrMsg = '';
return
} else {
this.carrierNameError = true;
this.carrierNameErrMsg = 'Incorrect email format';
}
},
}
})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>
<body>
<div id="app">
<div class="form-control invoice-form" :class="{ 'is-invalid': carrierEmailError }">
<input v-model="carrierEmail" #blur="blur('carrierEmail')" #focus="focus('carrierEmail')" type="text" placeholder="E-MAIL">
</div>
<div class="invalid-feedback" v-show="carrierEmailError">
{{ carrierEmailErrMsg }}
</div>
<div class="form-control invoice-form" :class="{ 'is-invalid': carrierNameError }">
<input v-model="carrierName" #blur="blur('carrierName')" #focus="focus('carrierName')" type="text" placeholder="name">
<div class="ic-clear" #click="clearField('carrierName')"></div>
</div>
<div class="invalid-feedback" v-show="carrierNameError">{{ carrierNameErrMsg }}</div>
</div>
</body>
</html>

VueJS , LoDash debounce watch on entire form

I'm trying to get LoDash debounce to work to trigger an event when a user stops typing on a form.
Something similar to this guide
Except I want to apply it to the entire form/model properties.
At the moment the debounce never fires.
Example JS Fiddle
JS
new Vue({
el: "#app",
data() {
return {
form: {
user: {
name: "Bob",
email: "Test#test.com"
}
},
isTyping: false,
isLoading: false,
}
},
watch: {
form: _.debounce(function() {
this.isTyping = false;
}, 1000),
isTyping: function(value) {
if (!value) {
console.log("stopped typing")
}
}
},
methods: {
}
})
HTML
<div id="app" class="container-fluid">
<div class="row">
<div class="col-md-3">
<label class="control-label">Name</label>
<input type="text" class="form-control" #input="isTyping = true" v-model="form.user.name" placeholder="Type your keyword">
<label class="control-label">Email</label>
<input type="text" class="form-control" #input="isTyping = true" v-model="form.user.email" placeholder="Type your Email">
</div>
</div>
</div>
You need to make your watcher deep
form: {
handler: _.debounce(function() {
this.isTyping = false;
}, 1000),
deep: true
},
Updated fiddle

Categories