$watch do not handling mutations in VueJS Component prop - javascript

I'm using Vue.js v1.0.24. In component Vue.component I have a prop events and handling this using:
Vue.component('my-component', {
template: '<div id="my-component"></div>',
props: {
events: {
type: Array,
required: true
},
event: {
type: Object,
required: true
}
},
ready: function() {
// ...
this.$watch('events', function (value, mutation) {
if (mutation) {
console.log(
mutation.method,
mutation.args,
mutation.result,
mutation.inserted,
mutation.removed)
}
})
},
//...
}
Whenever I push something in events, the $watch triggers, but the result is:
undefined undefined undefined undefined undefined
Does anyone know what is wrong?

Related

Why Vue can't watch the data change?

i want the function:createComparation work when tableRowName change,but acturely when tableRowName change , it didnt works,vue follows;
createComparation is another function which didnt define by vue but only by javascript
const selectedRight =Vue.createApp({
data(){
return {
tableRow:0,
tableRowName:[],
stockName:[],
rectWidth:40,
rectHeight:5,
}
},
watch: {
tableRowName(newtable,oldtable){
console.log(1)
createComparation()
},
immediate:true,
stockName(){
changeTip()
},
},
methods:{
}
}).mount('#selectedRight')
in case of tableRowName contain objects then you have to use
deep:true
watch: {
tableRowName(newtable,oldtable){
console.log(1)
createComparation()
},
immediate:true,
deep: true,
stockName(){
changeTip()
},
},
but i think you are updating the array without reactive manner, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g.
vm.items.length = newLength
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // is NOT reactive
vm.items.length = 2 // is NOT reactive
I guess whatching array might be the issue. You can try this:
computed: {
rowNames() {
return this.tableRowName;
// if the line above doesn't work:
return this.tableRowName.join();
}
},
watch: {
rowNames(newtable,oldtable){
createComparation()
},
I think this is what you're looking for. You need to define the handler as an object for the property you're trying to watch and set immediate: true.
Vue.config.productionTip = false
Vue.config.devtools = false
new Vue({
el: "#app",
data() {
return {
tableRow: 0,
tableRowName: [],
stockName: [],
rectWidth: 40,
rectHeight: 5,
}
},
watch: {
tableRowName: {
handler(newtable) {
console.log('Calling createComparation function');
console.info(newtable);
},
immediate: true
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="tableRowName.push(Math.random())">Trigger change manually again</button>
</div>
The watch method definition is wrong. When you need to use immediate, you have to put you function body into handler property.
For example,
watch: {
tableRowName: {
handler: function() {
},
immediate: true
}
},

I failed to call component's method inside of vue-froala-wysiwyg event

in laravel 8/2.6/bootstrap 4.6/Axios app using vue-froala-wysiwyg I need to get content of entered text and
call component's method with entered text.
I define event as I read here https://github.com/froala/vue-froala-wysiwyg :
import VueFroala from 'vue-froala-wysiwyg' // https://froala.com/wysiwyg-editor/docs
Vue.use(VueFroala) // https://github.com/froala/vue-froala-wysiwyg
Vue.config.productionTip = false
// let self = this
export default {
name: "RoomChat",
components: {},
data() {
return {
currentRoom: null,
...
froalaEditorConfig: {
events: {
initialized: function () {
console.log('froalaEditorConfig initialized')
},
'contentChanged': function () { // https://froala.com/wysiwyg-editor/docs/events/
console.log('froalaEditorConfig contentChanged this::')
// this - is reference to froala component
console.log(this);
console.log('this.el::')
// I tryied to get ref to root component in several ways
console.log(this.el) // undefined
console.log('this.el.$parent::')
console.log(this.el.$parent) // undefined
console.log('this.$parent::')
console.log(this.$parent) // undefined
console.log('froalaEditorConfig contentChanged this.html.get()::')
console.log(this.html.get());
parent.actionUser(this.html.get()) // I got parent.actionUser is not a function error
},
},
},
...
methods: {
actionUser(enteredText) {
...
Which way is valid?
ADDED :
Searching for decision I found
https://medium.com/dataseries/vue-js-components-parent-child-and-root-f1fcbe422feb
article with this.$root described but making inside of my event :
console.log('this.$root::')
console.log(this.$root)
Undefined is outputted.
What I see inside of event outputting this : https://prnt.sc/1r6pp4y and https://prnt.sc/1r6ptoh
Thanks!
I found decision with sending vueComponent instance as parameter :
data:(vm) => ({
...
froalaEditorConfig: {
events: {
initialized: function () {
},
contentChanged () {
vm.actionUser(this.html.get()) // That works ok
},
},
....
},
}), // data(vm) => ({

"Cannot read property 'props' of undefined" while mounting functional Vue component

Case:
I am trying dynamically mount functional vue component inside custom directive
(I need to show special button, when user hovers on some elements on the page). I do it in this way, dynamically, because I have thousands of elements on the page, so I try to avoid excess components and try to mount them on the fly, while hovering.
Directive code:
import AIcon from './ui/AIcon';
let AIconComponent = Vue.extend(AIcon);
editable: {
bind: (element, binding, vNode) => {
element.addEventListener('mouseover', () => {
element.style.position = 'relative';
let editButtonWrp = htmlToElement(`<div class="btn-wrp"><span class="btn"></span></div>`);
element.prepend(editButtonWrp);
new AIconComponent({
el: editButtonWrp.querySelector('.btn'),
parent: vNode.context,
props: {
size: 'xs', icon: 'edit',
},
});
});
}
}
Button functional component code:
export default {
functional: true,
props: {
icon: {
type: String,
default: '',
},
size: {
type: String,
default: 'md',
}
},
render(createElement, { props }) {
let iconHref = `/dist/img/sprite.svg#${props.icon}`;
return createElement('svg', {
class: { 'a-icon': true, [`-${props.icon}`]: true },
}, [
createElement('use', {
attrs: {
'xlink:href': iconHref,
},
}),
]);
},
}
But on the page I get this error:
TypeError: Cannot read property 'props' of undefined
at Proxy.render (AIcon.js?27d5:19)
As I understand, when I call new AIconComponent({ ... }) in directive, it passes undefind context to render(createElement, { props }) ... but why? How I can resolve this case?

How can I refactor repetitive conditional Vue.js code?

I have this code in my Vue.js component:
mounted() {
if (localStorage.dobDate) {
this.form.dobDate = localStorage.dobDate;
}
if (localStorage.dobMonth) {
this.form.dobMonth = localStorage.dobMonth;
}
if (localStorage.dobYear) {
this.form.dobYear = localStorage.dobYear;
}
},
watch: {
"form.dobDate": {
handler: function(after, before) {
localStorage.dobDate = after;
},
deep: true
},
"form.dobMonth": {
handler: function(after, before) {
localStorage.dobMonth = after;
},
deep: true
},
"form.dobYear": {
handler: function(after, before) {
localStorage.dobYear = after;
},
deep: true
}
Ask you can see it can get very repetitive, if for example I had a large form, and I don't want to do this for every field. Is there a way I can approach this to make it more DRY? Is there a way I can make it more dynamic for any field in a form for example?
In the mounted hook create an array of localStorage fields ["dobDate","dobMonth","dobYear"] and loop through it using forEach method, for each field localStorage[fieldName] check if it's defined using conditional operator, if it's defined assign it to the correspondant field name in the form data property else pass to the next element:
mounted(){
["dobDate","dobMonth","dobYear"].forEach(field=>{
localStorage[field]?this.form[field]=localStorage[field]:{};
})
}
In the watch property watch the form object deeply (watch its nested fields) then loop through its keys by doing the reciprocal operation made in mounted hook :
watch: {
form: {
handler: function(after, before) {
Object.keys(after).forEach(key=>{
localStorage[key]=after[key]
})
},
deep: true
}
}
Here is another approach with multiple (no deep) watchers.
data: {
form: {},
dateFields: ['dobDate', 'dobMonth', 'dobYear']
},
mounted() {
for (const dateField of this.dateFields) {
if (localStorage[dateField])
this.$set(this.form, dateField, localStorage[dateField])
}
},
created() {
for (const dateField of this.dateFields) {
this.$watch('form.' + dateField, function(after, before) {
localStorage[dateField] = after;
});
}
}
I ignore if it's more or less efficient than only one deep watcher. It may depends on the way your data change.
I'm sure you must have reasons for using localStorage for saving form data in localStorage, so with this code, you can pass the whole form object to localStorage and can retrieve that. in this case, any change in form would make this watch run
mounted() {
if (localStorage.form) {
this.form = localStorage.form
}
},
watch: {
"form": {
handler: function(after, before) {
localStorage.form = after;
},
deep: true
}
}

Update data property / object in vue.js

is there a way I can programmatically update the data object / property in vue.js? For example, when my component loads, my data object is:
data: function () {
return {
cars: true,
}
}
And after an event is triggered, I want the data object to look like:
data: function () {
return {
cars: true,
planes: true
}
}
I tried:
<script>
module.exports = {
data: function () {
return {
cars: true
}
},
methods: {
click_me: function () {
this.set(this.planes, true);
}
},
props: []
}
</script>
But this gives me the error this.set is not a function. Can someone help?
Thanks in advance!
Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object, So you may create an object and add a new property like that:
data: function () {
return {
someObject:{
cars: true,
}
}
and add the property with the vm.$set method:
methods: {
click_me: function () {
this.$set(this.someObject, 'planes', true)
}
}
for vue 1.x use Vue.set(this.someObject, 'planes', true)
reactivity

Categories