How to watch for Vue instance property inside component? - javascript

I have a plugin that adds some property to Vue instance.
Then I can access this property inside components using this.$plugin.prop. How can I watch for its changes? I need to do something inside component based on this.$plugin.prop value but neither watch or this.$watch worked for me. I assume its because watch works in component context so I can't watch for variable outside component, for example
mounted() {
this.$watch('$plugin.prop', val => console.log(val));
}
doesn't work.
What is the right way to accomplish this?

Instead of mounted() try
watch: {
'$plugin.prop': function(value){
console.log(value);
}
}
The offical documentation on watchers in the Vue docs

You may use computed properties instead like so:
computed: {
pluginChanged() {
console.log(this.$plugin.prop.val);
return this.$plugin.prop.val;
}
Read more about computed properties here.

Related

Why is this Vue prop not reacting to change?

I have a Prop in my component that is a User object, I then have this function:
onChange: function(event){
this.$v.$touch();
if (!this.$v.$invalid) {
this.$axios.put('update',{
code:this.user.code,
col:event.target.name,
val:event.target.value
}).then(response => {
this.user[event.target.name]=event.target.value
});
}
}
I can see in the Vue console debugger that the correct attribute has been updated, this attribute exists when the component is created but the template where I reference it does not refresh:
<p>Hi {{user.nickname}}, you can edit your details here:</p>
This is all within the same component so I'm not navigating to child or parent. I'm sure props have been reactive elsewhere in my code?
Ok, it seems this is intended behaviour. According to the documentation
https://v2.vuejs.org/v2/guide/components-props.html in the scenario that I have it should be handled as:
The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. In this case,
it’s best to define a local data property that uses the prop as its
initial value:
props: ['initialCounter'],
data: function () {
return {
counter: this.initialCounter
}
}
Usually components should be reactive to Props, though i have had experiences where it was non-reactive so i added the prop to a watcher and put the functional call there.
props: ["myProp"],
watch:{
myProp(){
// ... your functions here
}
}

why can't use window in vue template?

i set a property in window Object for using it globally, like this:
window.configs.foo=true;
but when use it like this:
<v-btn v-if="window.configs.foo">go</v-btn>
in console, i get this error:
[Vue warn]: Property or method "window" is not defined on the instance
but referenced during render. Make sure that this property is
reactive, either in the data option, or for class-based components, by
initializing the property.
how i can use window object in vueJs template?
Because v-if is intended to be used on properties of your component. You cannot v-if over variables in global scope, or outside your component data or properties.
What you can do, instead, if to setup a computed property on your component that targets window.configs.foo:
new Vue({ // or maybe a component, this depend on how you're using it
template: `<div>
<v-btn v-if="showMyButton">...</v-btn>
</div>`
computed: {
showMyButton() {
return window.configs && window.configs.foo;
}
}
})
UPDATE:
If you have to reuse this in a lot of sites, there are two things that you can do:
Vuex
Using vuex to set the showMyButton as a vuex state. Then you can access it via:
v-if="$store.state.showMyButton"
And you can modify it via standard vuex mutations.
 Mixins
Maybe for some reason you don't want to use vuex. Then a way to reuse logic across many components is to use mixins.
const configAwareMixin = {
computed: {
showButton() {
return window.configs.foo;
}
}
}
// And then in your component:
Vue.component('stuff', {
mixins: [buttonAwareMixin],
template: `<div><v-btn v-if="showButton"></v-btn></div>`
})
Well, Alternate is to use $root in Vue. Define foo at your vue instance and it will be available in all the component with this.$root.foo.
Here is the official docs
Hope this helps
The only easiest solution is Vue.prototype.$window = window; in main.js from folder src and use can use window as $window inside your template. Hope can help you all.
I solved it by replacing the 'vue.js' with 'vue.min.js'! I don't know why.

Vue.js/Vuex: Calling getter vs Accessing state value directly on create lifecycle hook

I'm using the created lifecycle hook in vue.js to load data from my store to the data for a vue component. I noticed that this.selectedType = store.state.selectedType successfully loads the data from the store. However, if I use the getter to load from the store (i.e. this.selectedType = store.getters.getType()), I get the following error:
Error in created hook: "TypeError: Cannot read property 'selectedType' of undefined"
I don't understand why it is saying that selectedType is undefined because selectedType has the value "Item" in the store and is correctly loaded on create if I use this.selectedType = store.state.selectedType.
The getter is defined as such:
getters: {
getSelectedType: state => {
return state.selectedType
}
}
And the state is defined as:
state: {
selectedType: "Item"
}
Could someone please explain why this occurs? I'm hunch is that there is something about the lifecycles that I don't fully understand that is leading to this confusion.
You are not supposed to call getters. Just like computed properties, you instead write it like you are reading a variable. In the background the function you defined in the Vuex store is called with the state, getters (and possibly rootState and rootGetters) and returns some value.
Beside that, it is usually an anti-pattern to use a lifecycle hook to initialise any variable. Local 'component' variables can be initialised in the data property of the component, while things like the vuex state usually end up in a computed property.
The last thing I want to point out is that, if you have correctly added the store to your Vue application, you can access the store in any component with this.$store. To use getters in your application, you can use the mapGetters helper to map getters to component properties. I would recommend using something like this:
import { mapGetters } from 'vuex';
export default {
// Omitted some things here
computed: {
...mapGetters({
selectedType: 'getSelectedType'
})
},
methods: {
doSomething () {
console.log(this.selectedType);
}
}
}
Which is functionally equivalent to:
computed: {
selectedType () {
return this.$store.getters.getSelectedType;
}
}

how to use watch function in vue js

could you please tell me how to use watch function in vue js .I tried to used but I got this error.
vue.js:485 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "m"
found in
---> <AddTodo>
<Root>
https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview
I created different components and watch properties in the main component
var AddTODO = Vue.extend({
template: '#add-todo',
props: ['m'],
data: function () {
return {
message: ''
}
},
methods: {
addTodo: function () {
console.log(this.message)
console.log(this.m);
this.m =this.message;
},
},
});
When I try to add item I am getting this error.
Step to reproduce this bug
Type anything on input field and click on Add button
this.m =this.message;
this line is the issue,
It's recommended that you don't modify prop directly...
instead create a data property and then modify it.
It shows warning because you're modifying the prop item, prop value will be overwritten whenever the parent component re-renders.
The component's props are automatically updated in the component as soon as you change their value outside of it.
For this reason, trying to change the value of a property from inside your component is a bad idea: you should use the props as read-only.
If you want to use a prop as the initial value of some of your component's data you can simply declare it this way:
data: function () {
return {
changeable: this.receivedProp;
}
},
That being said, if you are trying to change the value of a prop from inside a component to be able to use your reassigned prop outside of it, you are doing it the wrong way. The way you should handle this is by using Vue's custom events.
Remember, as Vue's documentation states:
In Vue, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events.

How to get changes in Vue updated hook?

If I have a Vue component like:
<script>
export default {
updated() {
// do something here...
}
};
</script>
is there anyway to get the changes that resulted in the update? Like how watch hooks accept arguments for previous and next data?
watch: {
someProp(next, prev) {
// you can compare states here
}
}
React seems to do this in componentDidUpdate hooks, so I'm assuming Vue has something similar but I could be wrong.
The updated lifecycle hook doesn't provide any information on what caused the Vue component instance to be updated. The best way to react to data changes is by using watchers.
However, if you're trying to investigate what caused an update for debugging purposes, you can store a reference to the state of the Vue instance's data and compare it to the state when updated.
Here's an example script using lodash to log the name of the property that changed, triggering the update:
updated() {
if (!this._priorState) {
this._priorState = this.$options.data();
}
let self = this;
let changedProp = _.findKey(this._data, (val, key) => {
return !_.isEqual(val, self._priorState[key]);
});
this._priorState = {...this._data};
console.log(changedProp);
},
This works because properties prepended with the underscore character are reserved for internal use and are not available for binding. This could be saved in a mixin to use whenever you needed to debug a Vue component this way.
Here's a working fiddle for that example.

Categories