I have Vue component here
Vue.component('number-input', {
props: {},
template: `<textarea class="handsontableInput subtxt area-custom text-center text-bold" v-model="displayValue" #blur="isInputActive = false" #focus="isInputActive = true"></textarea>`,
data: function() {
return {
isInputActive: false
}
},
computed: {
displayValue: {
get: function() {
if (this.isInputActive) {
return this.value.toString()
} else {
return this.value.toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
}
},
set: function(modifiedValue) {
let newValue = parseFloat(modifiedValue.replace(/[^\d\.]/g, ""))
if (isNaN(newValue)) {
newValue = 0
}
this.$emit('input', newValue)
}
}
}
})
and have methods change on vue instance as bellow
var content_kalkulasi = new Vue({
el: '#kalkulasi-table',
data: {
arr: [{id:'',name:'',file:'',satuan: 0,sub: 0}],
total: 0,
index_upload: 0
},
methods:{
add(){
arr = {}
arr.id = ''
arr.name = ''
arr.file = ''
arr.satuan = 0
arr.sub = 0
this.arr.push(arr)
},
change(){
this.total = 0
for(x in this.arr){
this.total += this.arr[x].satuan * this.arr[x].sub
}
console.log(this.total)
},
And I want to trigger method change from this html
<number-input style="" v-model="data.sub" v-on:keyup="change"></number-input>
butv-on:keyup="change" wont triggering. How i can call method v-on:keyup="change" from vue component? thank you
It is because your component isn't firing the keyup event.
Change v-on:keyup="change" to v-on:input="change"
Or in your component add this to the textarea :
#keyup="$emit('keyup')"
Related
I'm using ckeditor5 balloon block mode in nuxt project.
I have used online builder and downloaded build files , add the build files to my project and importing them into my editor component and using it!
the only problem that I have is that when the page loads ,
I get an error : editor-isreadonly-has-no-setter.
I tried binding v-model to the editor but the value won't be updated!
note : I have used ckeditor5 classic mode identical to the way that I'm using Balloon Block, donno really what's going on!
this is my component :
<template>
<ckeditor
:id="id"
v-bind="$attrs"
:editor="BalloonBlock"
:config="editorConfig"
v-on="$listeners"
/>
</template>
<script>
let BalloonBlock
let CKEditor
if (process.client) {
BalloonBlock = require('#/plugins/ckeditor/ckeditor')
CKEditor = require('#ckeditor/ckeditor5-vue2')
} else {
CKEditor = { component: { template: '<div></div>' } }
}
export default {
name: 'CKEditor',
components: {
ckeditor: CKEditor.component,
},
props: {
fillErr: {
type: Boolean,
default: false,
required: false,
},
minHeight: {
type: String,
default: '350px',
required: false,
},
label: {
type: String,
default: '',
required: false,
},
},
data() {
return {
classicEditor: BalloonBlock,
editorConfig: {
language: 'fa',
contentsLangDirection: 'rtl',
},
editorElement: null,
id: null,
}
},
computed: {
value() {
return this.$attrs.value
},
},
created() {
this.id = this.uuidv4()
},
mounted() {
if (!document.getElementById('editorFaTranslate')) {
const faScript = document.createElement('script')
faScript.setAttribute('charset', 'utf-8')
faScript.setAttribute('type', 'text/js')
faScript.setAttribute('id', 'editorFaTranslate')
faScript.setAttribute(
'src',
require('##/plugins/ckeditor/translations/fa.js')
)
document.head.appendChild(faScript)
}
const intervalId = setInterval(() => {
const ckEditor = document.getElementById(this.id)
if (ckEditor) {
clearInterval(intervalId)
this.editorElement = ckEditor
}
})
},
methods: {
uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
const r = (Math.random() * 16) | 0
const v = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
}
)
},
insertTextAtTheEnd(text) {
function findCorrectPosition(htmlStr) {
const lastIndexOfHTMLTag = htmlStr.lastIndexOf('</')
const lastUlTag = htmlStr.lastIndexOf('</ul>')
const lastOlTag = htmlStr.lastIndexOf('</ol>')
if (
lastUlTag === lastIndexOfHTMLTag ||
lastOlTag === lastIndexOfHTMLTag
) {
const lastLiTag = htmlStr.lastIndexOf('</li>')
return lastLiTag
}
return lastIndexOfHTMLTag
}
const currentString = this.value
const correctIndex = findCorrectPosition(currentString)
const firstHalf = currentString.substring(0, correctIndex)
const secondHalf = currentString.substring(correctIndex)
const newString = `${firstHalf}${text}${secondHalf}`
this.$emit('input', newString)
},
},
}
</script>
I would welcome any idea!
I added "#ckeditor/ckeditor5-vue2": "github:ckeditor/ckeditor5-vue2", in my dependencies and all of a sudden my problem was gone!
I created a custom timer component, but I got errors about vuex store.
This component starts a timer when it's created and put into the store, then each minute it increments the time. If the person leaves the page like the timer is in the store, the time is saved and when the person comes back to the page, the timer resume by itself.
This is my component
<template>
<div>
<v-icon v-if="timer.visibility" :color="timeColor" #click="changeTimer">
{{ $icons.clock }}
</v-icon>
</div>
</template>
<script>
export default {
props: {
value: {
type: Number,
required: true
},
id: {
type: Number,
default: null
},
type: {
type: String,
default: null
}
},
data() {
return {
timer: {
actif: false,
visibility: false,
timeOut: null,
dateDebut: null,
id: 0
}
}
},
computed: {
listeTimer() {
return this.$store.state.listeTimerPointage
},
timeColor() {
return this.timer.actif ? 'green' : 'red'
},
count: {
get() {
return this.value
},
set(val) {
this.$emit('input', val)
}
}
},
beforeDestroy() {
this.stopTimer()
},
created() {
let precedentTimer = null
if (this.id > 0) {
if (this.listeTimer.length > 0) {
precedentTimer = this.listeTimer.filter((f) => f.id === this.id)
}
} else {
this.timer.id = 0
}
this.startTimer(precedentTimer)
},
methods: {
// Start le timer
startTimer(precedentTimer) {
if (precedentTimer !== null) {
this.timer = precedentTimer
this.count = precedentTimer.count
} else {
this.count = 1
this.timer.dateDebut = new Date()
if (this.timer.timeOut === null) {
this.timer.actif = true
this.timer.visibility = true
this.timer.timeOut = setTimeout(() => {
this.timerBoucle()
}, 60000)
}
}
// this.listeTimer.push(this.timer)
this.$store.commit('addListeTimerPointage', this.timer)
},
// Arrete le timer
stopTimer() {
this.timer.actif = false
clearTimeout(this.timer.timeOut)
},
// Met en place la boucle toute les 1 minutes
timerBoucle() {
const now = new Date()
const diff = now - this.timer.dateDebut
this.count += Math.round(diff / 60000)
this.timer.dateDebut = new Date()
this.timer.timeOut = setTimeout(() => {
this.timerBoucle()
}, 60000)
},
// Modifie l'état du timer
changeTimer() {
this.timer.actif = !this.timer.actif
if (!this.timer.actif) {
clearTimeout(this.timer.timeOut)
} else {
this.timer.dateDebut = new Date()
this.timer.timeOut = setTimeout(() => {
this.timerBoucle()
}, 60000)
}
}
}
}
</script>
I indeed mutate a state, but I don't think I change the state directly
And this is the store:
addListeTimerPointage(state, data) {
state.listeTimerPointage.push(data)
},
deleteTimer(state, data) {
const newArray = state.listeTimerPointage.filter(
(item) => item.id !== data
)
state.listeTimerPointage = newArray
}
Thanks for your help
I am creating undo/redo functionality in VueJS. I watch the settings and add a new element to an array of changes when the settings change. I also have a method for undo when the undo button is clicked.
However, when the button is clicked and the last setting is reverted, the settings are changed and the watch is fired again.
How can I prevent a new element being added to the array of changes if the settings changed but it was because the Undo button was clicked?
(function () {
var Admin = {};
Admin.init = function () {
};
var appData = {
settings: {
has_border: true,
leave_reviews: true,
has_questions: true
},
mutations: [],
mutationIndex: null,
undoDisabled: true,
redoDisabled: true
};
var app = new Vue({
el: '#app',
data: appData,
methods: {
undo: function() {
if (this.mutations[this.mutationIndex - 1]) {
let settings = JSON.parse(this.mutations[this.mutationIndex - 1]);
this.settings = settings;
this.mutationIndex = this.mutations.length - 1;
console.log (settings);
}
},
redo: function() {
}
},
computed: {
border_class: {
get: function () {
return this.settings.has_border ? ' rp-pwb' : ''
}
},
undo_class: {
get: function () {
return this.undoDisabled ? ' disabled' : ''
}
},
redo_class: {
get: function () {
return this.redoDisabled ? ' disabled' : ''
}
}
},
watch: {
undoDisabled: function () {
return this.mutations.length;
},
redoDisabled: function () {
return this.mutations.length;
},
settings: {
handler: function () {
let mutation = JSON.stringify(this.settings),
prevMutation = JSON.stringify(this.mutations[this.mutations.length-1]);
if (mutation !== prevMutation) {
this.mutations.push(mutation);
this.mutationIndex = this.mutations.length - 1;
this.undoDisabled = false;
}
},
deep: true
}
}
});
Admin.init();
})();
Since you make the changes with a button click, you can create a method to achieve your goal instead of using watchers.
methods: {
settings() {
// call this method from undo and redo methods if the conditions are met.
// move the watcher code here.
}
}
BTW,
If you don't use setter in computed properties, you don't need getters, so that is enough:
border_class() {
return this.settings.has_border ? ' rp-pwb' : ''
},
These watchers codes look belong to computed:
undoDisabled() {
return this.mutations.length;
},
redoDisabled() {
return this.mutations.length;
},
I created a component and a module for a functionality X and I'm using Vuex for state management. The code works for the every first time insertion, but after this the Getter function always returns the same value of the input before the action ends and commit the mutation.
For example:
1 - everything is [0,0,0] and Getter is [0,0,0]. Insert 9 in the first position and the value is inserted.
2 - On the second time, the check if the value inserted is equal of what is on the state returns true, so we had to remove this verification.
By the way, the state continues to be modified without the action commit the changes to mutation, and when we look to the Getter (who retrieves the value from the state) the value inserted is already returned by the Getter.
Someone know how to fix this?
Here is the code
component:
Vue.component('profundidade-cell', {
data: function () {
return {
valorProfundidade: [0, 0, 0],
id: this.face + '-' + this.dente,
ids: [
this.face + '-profundidade-sondagem-' + this.dente + '-1',
this.face + '-profundidade-sondagem-' + this.dente + '-2',
this.face + '-profundidade-sondagem-' + this.dente + '-3'
],
changedId: null,
valorInserido: null,
valorAnt: null,
}
},
props: {
arcada: String,
sextante: String,
dente: String,
face: String,
face_json: String,
max_length: Number,
min_value: Number,
max_value: Number,
},
computed: {
profundidadeSondagem() {
return store.getters['profundidadeSondagem/profundidadeSondagem']({arcada: this.arcada,
sextante: this.sextante, dente: "dente_" + this.dente, face: this.face_json});
},
presente() {
return store.getters.dentePresente({arcada: this.arcada, sextante: this.sextante,
dente: "dente_" + this.dente});
}
},
created: function() {
this.debouncedAlterarProfundidade = _.debounce(this.alterarValorProfundidadeSondagem, 400);
this.$root.$on("vuex-carregado", this.carregar);
},
methods: {
getValue(e) {
this.changedId = e.target.id;
this.valorInserido = e.target.value;
this.debouncedAlterarProfundidade();
},
alterarValorProfundidadeSondagem() {
let modelRefs = {};
let patologia = {
arcada: this.arcada,
sextante: this.sextante,
dente: "dente_" + this.dente,
face: this.face_json,
valor: this.valorProfundidade,
modelRefs: modelRefs,
id: this.changedId,
valorInserido: this.valorInserido,
};
store.dispatch('profundidadeSondagem/MODIFY', patologia).catch(() => {
this.valorProfundidade = this.profundidadeSondagem;
})
},
carregar(){
this.valorProfundidade = this.profundidadeSondagem;
}
},
template: `
<div>
<input type="text" :id=ids[0] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[0] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
<input type="text" :id=ids[1] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[1] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
<input type="text" :id=ids[2] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[2] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
</div>
`
});
module:
const moduleProfundidadeSondagem = {
namespaced: true,
actions: {
MODIFY({commit, dispatch, getters, rootGetters}, obj) {
let patologia = {
face: rootGetters.getNomeFace(obj.face),
dente: rootGetters.getNomeDente(obj.dente),
local: "FACE",
ficha: this.state.idPeriograma,
descricao: obj.valor.toString(),
paciente: this.state.idPaciente,
tipo: 'PROFUNDIDADE_DE_SONDAGEM'
};
if(obj.valor) != getters.profundidadeSondagem(obj)) {
let reg = new RegExp(/([0-9],[0-9],[0-9])/);
let param = null;
return new Promise((resolve, reject) => {
if(obj.valor[0] == 0 && obj.valor[1] == 0 && obj.valor[2] == 0) {
param = axios.delete('/patologia', {data: patologia});
} else if (reg.test(obj.valor)){
param = axios.post('/patologia', patologia);
}
if(param != null) {
param.then(function (response) {
if(response.status == 200 || response.status == 201 && response.data) {
commit('armazenarProfundidadeSondagem', obj);
let dentes_data = {};
let face = '';
if (obj.arcada == 'arcada_superior' && obj.face == 'face_lingual_palatal') {
face = 'palatina'
} else {
face = obj.face.split('_')[1];
}
let classe_canvas = rootGetters.getNomeClasseCanvas(obj, face);
drawGraph(rootGetters.prepareDentesData(obj, face, dentes_data), face,
classe_canvas);
resolve();
}
}).catch(error => {
store.dispatch('mensagemAlerta/ALERTA', {
tipo: 'error',
mensagem: 'Não foi possível cadastrar o nível de sondagem'
});
reject(error);
});
}
})
}
},
RESET_PROFUNDIDADE_SONDAGEM({commit}, ob) {
commit('RESET_ALL', ob);
}
},
getters: {
profundidadeSondagem: (state, getters, rootState) => obj => {
return rootState[obj.arcada][obj.sextante][obj.dente][obj.face].profundidade_sondagem;
}
},
my guess is your issue lies here:
TL;DR - you pass your getter as valor to your action.
only a guess - as i cant debug your code
store.dispatch('profundidadeSondagem/MODIFY', patologia).catch(() => {
this.valorProfundidade = this.profundidadeSondagem;
})
as you assign a reference from your rootState[...] and thus you change the properties of the rootState[...] in your component past the first run.
So your code then behaves like:
let patologia = {
arcada: this.arcada,
sextante: this.sextante,
dente: "dente_" + this.dente,
face: this.face_json,
// valor: this.valorProfundidade,
///* same as */ valor: this.profundidadeSondagem,
/* same as */ valor: this.$store.getters['profundidadeSondagem/profundidadeSondagem'](...),
modelRefs: modelRefs,
id: this.changedId,
valorInserido: this.valorInserido,
};
A solution can be to this.valorProfundidade = this.profundidadeSondagem.slice(); as long it is an array or Object.assign({},...) - so you prevent the references
i want to make two button to input number.
but when the left one goes to 10, it looks like this:
enter image description here
i want it to be 2 on the left while 0 on the right side.
so i changed my code:
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal2"></button-counter>
<button-counter v-on:increment2="incrementTotal"></button-counter>
</div>
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button><button v-on:click="increment2">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment')
},
increment2:function () {
if(this.counter === 10){
this.counter = 0;
this.increment();
}
this.$emit('increment2')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
},
incrementTotal2: function () {
this.total = this.total +10
}
}
})
but it did'nt work..enter image description here
i click the right button, the total number wont change.
You render 2 components each of them should render 2 buttons. Sounds about right? If you check Element Inspector you will see that rendered only 2 buttons. 2 + 2 === 2 - something is fishy...
Dev version of Vue telling you in console "Error compiling template... Component template should contain exactly one root element".
So each button-counter render first button => writing you warning => and ignoring second button.
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter-1 #increment="incrementTotal"></button-counter-1>
<button-counter-2 #increment="incrementTotal"></button-counter-2>
</div>
Vue.component('button-counter-1', {
template: '<button #click="increment1">{{ counter }}</button>',
data: function() {
return { counter: 0 }
},
methods: {
increment1: function () {
this.counter++;
this.$emit('increment', 10);
}
}
});
Vue.component('button-counter-2', {
template: '<button #click="increment2">{{ counter }}</button>',
data: function() {
return { counter: 0 }
},
methods: {
increment2: function () {
this.counter++;
this.$emit('increment', 1);
}
}
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function (n) {
this.total += n;
},
}
})