How do I make reactive global property in vuejs plugin? - vuejs2

I put $testCounter in a plugin to make it global :
Vue.use({
install(Vue) {
Vue.prototype.$testCounter = 0;
Vue.prototype.$incrementCounter = () => {
Vue.prototype.$testCounter++;
};
});
I want to output it in some component. I also need its value to be updated globally, and reactively :
<template>
<p>{{ $testCounter }}</p>
</template>
<script>
mounted() {
let comp = this;
comp.watcherId = setInterval(() => {
comp.$incrementCounter();
// I want to remove this line and still be reactive :
comp.$forceUpdate();
}, 1000);
}
</script>
I need the property to be reactive, I tried a multiple solution as watchers, computed props, vm.$set(...), but I can't find the right way to do this.

Solution 1: use Vuex
Solution 2: set the global reactive data in root component and use it by calling this.$root
demo: https://jsfiddle.net/jacobgoh101/mdt4673d/2/
HTML
<div id="app">
<test1>
{{$root.testCounter}}
</test1>
</div>
Javascript
Vue.component('test1', {
template: `
<div>
test1
<slot></slot>
</div>
`,
mounted() {
setInterval(() => {
this.$root.incrementCounter();
}, 1000)
}
});
new Vue({
el: "#app",
data: {
testCounter: 1
},
methods: {
incrementCounter: function() {
this.testCounter++;
}
}
})

Related

How to fix Vue 3 template compilation error : v-model value must be a valid JavaScript member expression?

I am working on a vue project and the vue version is 3.0
And recently I can see these many warnings for some reason.
Template compilation error: v-model value must be a valid JavaScript member expression
I guess it is because I am using long v-model variable name like this.
<textarea v-model="firstVariable.subVariable.subVariableKey" readonly></textarea>
Please let me know if any idea.
Thanks in advance
This is the component and template code.
var myTemplate = Vue.defineComponent({
template: '#myTemplate',
data() {
return {
firstVariable: {}
}
},
mounted() {
loadData();
},
methods:{
loadData() {
axios.get(MY_ROUTES).then(res => {
// let's suppose res.data is going to be {subVariable: {subVariableKey: "val"}}
this.firstVariable = res.data;
})
}
}
});
// template.html
<script type="text/template" id="myTemplate">
<div class="container">
<textarea v-model="firstVariable.subVariable?.subVariableKey"></textarea>
</div>
</script>
In order that your property go reactive you've to define its full schema :
data() {
return {
firstVariable: {
subVariable: {
subVariableKey: ''
}
}
}
},
and use it directly without optional chaining
v-model="firstVariable.subVariable.subVariableKey"
because v-model="firstVariable.subVariable?.subVariableKey" malformed expression like v-model="a+b" like this test
Example
var comp1 = Vue.defineComponent({
name: 'comp1',
template: '#myTemplate',
data() {
return {
firstVariable: {
subVariable: {
subVariableKey: ''
}
}
}
},
mounted() {
this.loadData();
},
methods: {
loadData() {
}
}
});
const {
createApp
} = Vue;
const App = {
components: {
comp1
},
data() {
return {
}
},
mounted() {
}
}
const app = createApp(App)
app.mount('#app')
<script src="https://unpkg.com/vue#3.0.0-rc.11/dist/vue.global.prod.js"></script>
<div id="app" >
vue 3 app
<comp1 />
</div>
<script type="text/template" id="myTemplate">
<div class="container">
<textarea v-model="firstVariable.subVariable.subVariableKey"></textarea>
<div>
{{firstVariable.subVariable.subVariableKey}}
</div>
</div>
</script>
You are adding a new property to an object which is not reactive.
Vue cannot detect property addition or deletion. Since Vue performs
the getter/setter conversion process during instance initialization, a
property must be present in the data object in order for Vue to
convert it and make it reactive. For example:
Source
Instead of
this.firstVariable = res.data;
Use
this.$set(this.firstVariable, 'subVariable', res.data.subVariable);

How watch global variable in component vuejs?

I need global variables for errors. But I don't want set input variable for every component.
How I can watch $errors in component ABC without input variable?
(without <abc :errors="$errors"></abc>)
index.js:
Vue.prototype.$errors = {};
new Vue({
el: '#app',
render: h => h(App),
}
App.vue:
...
name: 'App',
components: {
ABC
}
...
methods:{
getContent() {
this.$errors = ...from axis...
}
Component ABC:
<template>
<div>{{ error }}</div>
</template>
...
watch: {
???
}
Here's an example of how it could be done:
const errors = Vue.observable({ errors: {} })
Object.defineProperty(Vue.prototype, '$errors', {
get () {
return errors.errors
},
set (value) {
errors.errors = value
}
})
new Vue({
el: '#app',
methods: {
newErrors () {
// Generate some random errors
const errors = {}
for (const property of ['name', 'type', 'id']) {
if (Math.random() < 0.5) {
errors[property] = 'Invalid value'
}
}
this.$errors = errors
}
}
})
new Vue({
el: '#app2',
watch: {
$errors () {
console.log('$errors has changed')
}
}
});
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<pre>{{ $errors }}</pre>
<button #click="newErrors">New errors</button>
</div>
<div id="app2">
<pre>{{ $errors }}</pre>
</div>
I've created two Vue instances to illustrate that the value really is shared. Clicking the button in the first instance will update the value of $errors and the watch is triggered in the second instance.
There are a few tricks in play here.
Firstly, reactivity can only track the reading and writing of properties of an observable object. So the first thing we do is create a suitable object:
const errors = Vue.observable({ errors: {} })
We then need to wire this up to Vue.prototype.$errors. By defining a get and set for that property we can proxy through to the underlying property within our observable object.
All of this is pretty close to how data properties work behind the scenes. For the data properties the observable object is called $data. Vue then uses defineProperty with get and set to proxy though from the Vue instance to the $data object, just like in my example.
as Estradiaz said:
You can use Vuex and access the value outside of Vue like in this answer: https://stackoverflow.com/a/47575742/10219239
This is an addition to Skirtles answer:
You can access such variables via Vue.prototype.variable.
You can set them directly, or use Vue.set, it works either way.
My code (basically the same as Skirtless):
main.js
const mobile = Vue.observable({ mobile: {} });
Object.defineProperty(Vue.prototype, '$mobile', {
get() { return mobile.mobile; },
set(value) { mobile.mobile = value; }
});
function widthChanged() {
if (window.innerWidth <= 768) {
if (!Vue.prototype.$mobile) Vue.set(Vue.prototype, '$mobile', true);
} else if (Vue.prototype.$mobile) Vue.set(Vue.prototype, '$mobile', false);
}
window.addEventListener("resize", widthChanged);
widthChanged();
Home.vue:
watch: {
'$mobile'(newValue) {
// react to Change in width
}
}

Change Vue prototype variable in all components

I'm wanting to change the global variable below throughout the page
Vue.prototype.$color = 'green';
I tried using the code below but it only changes within the component I created
watch: {
cor(newValue, oldVlue) {
this.$color = newValue;
}
}
is it possible for me to create a way to change the prototype variable across all components of the page?
To have $color globally available, you can use a Mixin, more specifically a Global Mixin.
If you would only want it to be read-only, it is simplest solution (less code). See snippet:
Vue.mixin({
created: function () {
this.$color = 'green';
}
})
new Vue({
el: '#app1',
data: {
message: 'Hello Vue.js!'
},
mounted() {
console.log('$color #app1:', this.$color);
}
})
new Vue({
el: '#app2',
data: {
message: 'Hello Vue.js!'
},
mounted() {
console.log('$color #app2:', this.$color);
}
})
<script src="https://unpkg.com/vue#2.5.15/dist/vue.min.js"></script>
<div id="app1">
<p>app1: {{ message }}</p>
</div>
<div id="app2">
<p>app2: {{ message }}</p>
</div>
Making $color reactive
To mave Vue react everywhere to changes to $color, you could use a Vuex store (see other answer).
But if you don't want to use Vuex just for that, another possibility is to create a Vue instance just to hold the "shared" data. After that, create a mixin with a computed property that references the $data of this "shared" Vue instance. See demo below.
// not using a Vuex store, but a separated Vue instance to hold the data
// only use this if you REALLY don't want to use Vuex, because Vuex is preferrable
let globalData = new Vue({
data: { $color: 'green' }
});
Vue.mixin({
computed: {
$color: {
get: function () { return globalData.$data.$color },
set: function (newColor) { globalData.$data.$color = newColor; }
}
}
})
// this.$color will be available in all Vue instances...
new Vue({
el: '#app1'
})
new Vue({
el: '#app2'
})
// ...and components
Vue.component('my-comp', {template: '#t3'});
new Vue({
el: '#app3',
})
<script src="https://unpkg.com/vue#2.5.15/dist/vue.min.js"></script>
<div id="app1">Color: {{ $color }} <button #click="$color = 'red'">change to red</button></div>
<div id="app2">Color: {{ $color }} <button #click="$color = 'yellow'">change to yellow</button></div>
<template id="t3">
<div>Color: {{ $color }} <button #click="$color = 'purple'">change to purple</button></div>
</template>
<div id="app3"><my-comp></my-comp></div>
For completeness, check below to see how using Vuex and Mixin would be (more details on how to use Vuex in the other answer).
// Using a Vuex to hold the "shared" data
// The store is not added to any instance, it is just referenced directly in the mixin
const store = new Vuex.Store({
state: { $color: 'green' },
mutations: { update$color: function(state, newColor) { state.$color = newColor; } }
});
Vue.mixin({
computed: {
$color: {
get: function() { return store.state.$color },
set: function(newColor) { return store.commit('update$color', newColor); }
}
}
})
// this.$color will be available in all Vue instances...
new Vue({
el: '#app1'
})
new Vue({
el: '#app2'
})
// ...and components
Vue.component('my-comp', {template: '#t3'});
new Vue({
el: '#app3',
})
<script src="https://unpkg.com/vue#2.5.15/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex#3.0.1/dist/vuex.min.js"></script>
<div id="app1">Color: {{ $color }} <button #click="$color = 'red'">change to red</button></div>
<div id="app2">Color: {{ $color }} <button #click="$color = 'yellow'">change to yellow</button></div>
<template id="t3">
<div>Color: {{ $color }} <button #click="$color = 'purple'">change to purple</button></div>
</template>
<div id="app3"><my-comp></my-comp></div>
If you want a reactive global variable, Mixins may not be a good idea. Because even if you are using global Mixins, Vue actually import and inject this Mixin whenever mount new components, which means every time a new variable $color created.
I believe the mutable data types (Object or Array) combined with Vue.prototype can do the trick:
In your main.js file:
Vue.prototype.$color = {value: "black"};
In your *.vue file:
this.$color.value = "red"
In another *.vue file:
console.log(this.$color.value); // "red"
Since you probably want $color to be a property that is not just available, but reactive (and the same) across all components, a possible solution is to use a quick/small Vuex store.
There's a runnable example below. In it you'll see three different Vue instances that will react to the same $color variable (that is at the Vuex store).
All three examples are functionally identical. I wrote them differently just to portrait different ways of using the API. Use what seems more intuitive for you.
const store = new Vuex.Store({
state: {
$color: 'green'
},
mutations: {
update$color: function(state, newColor) { state.$color = newColor; }
}
});
new Vue({
store: store, // add this so the store is available
el: '#app1',
// explicitly via this.$store
computed: {
$color: function() { return this.$store.state.$color }
},
methods: {
update$color: function(newColor) { return this.$store.commit('update$color', newColor); }
}
})
new Vue({
store, // shorthand for store: store
el: '#app2',
// using helpers mapState and mapMutations
computed: {
...Vuex.mapState(['$color'])
},
methods: {
...Vuex.mapMutations(['update$color'])
},
})
new Vue({
store,
el: '#app3',
// using computed properties, only
computed: {
$color: {
get: Vuex.mapState(['$color']).$color,
set: Vuex.mapMutations(['update$color']).update$color
}
},
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app1">
Color: {{ $color }} <button #click="update$color('blue')">change to blue</button> (explicitly via this.$store)
</div>
<div id="app2">
Color: {{ $color }} <button #click="update$color('red')">change to red</button> (using helpers mapState and mapMutations)
</div>
<div id="app3">
Color: {{ $color }} <button #click="$color = 'orange'">change to orange</button> (using computed properties, only)
</div>
If you want a global reactive variable, you can use this.$root inside child components. There is an example in vuejs docs:
// The root Vue instance
new Vue({
data: {
foo: 1
},
computed: {
bar: function () { /* ... */ }
},
methods: {
baz: function () { /* ... */ }
}
})
// Get root data
this.$root.foo
// Set root data
this.$root.foo = 2
// Access root computed properties
this.$root.bar
// Call root methods
this.$root.baz()
But consider using Vuex in most cases as official docs recommends.
Do this in the component as well
Vue.prototype.$color= 'colorName'
It worked for me.

Vue Component props value is does not seem on template

Everything is fine in my main.js
import User from './components/User.vue'
new Vue({
el: '#user',
render: h => h(User),
data() {
return {
groups: []
}
},
mounted() {
this.getGroups();
},
methods: {
getGroups: function () {
axios.get('http://vagrant.dev/groups')
.then(response => this.groups = response.data)
.catch(error => console.log(error));
}
}
});
User.vue
<template>
<div id="user">
{{groups}} <!-- must be printed but it doesn't seem -->
</div>
</template>
<script>
export default {
name: 'user',
props: ['groups']
}
</script>
and index.html
<div id="user">
<user :groups="groups"></user>
</div>
Where is the mistake?
I do not get any errors, but I didn't understand why the value was not printed on the screen
Seems like you are putting 2 Vue instances on the same template since in your main file you are defining the template as el: "#user" which is already controlled by User.vue.
In you index.html add a div with id="app" and in main.js set el: "#app"
Your main.js and index.html shouldn't mix template in HTML and render function. So your main.js should be:
```new Vue({
el: '#user',
components: { User },
data() {
return {
groups: []
}
},
...```
You shouldn't directly reassign data value because Vue cannot detect property additions and rerender view. You should do it via Vue.set or this.$set like this:
this.$set(this, 'groups', response.data)
You can read more about how vue reactive in https://v2.vuejs.org/v2/guide/reactivity.html and Vue.set API: https://v2.vuejs.org/v2/api/#Vue-set

VueJs how to get data from Vue.component

I want to know how to get data from Vue.component and send to
this >>var app = new Vue({ })<<
this is my code
Vue.component('my-form', {
template: '#my-form',
props:['ddTechtemp'],
data: function () {
return {
isCores: app.testCorres,
activeClass: 'isCorrespon',
errorClass: 'isTech',
tempData : {cell1 : "",
cell2 : "",
cell3 : "",
cell4 : "",
cell5 : "",
cell6 : ""
},
}
},
watch:{
tempData:{
handler:function(newVal,oldVal){
app.ddTechtemp = newVal;
},
deep:true,
}
},
methods:{
}});
I want to get data from above code and send to this code var app = new Vue({ data: Vue.component.data})
Anyone understand me please help.Thank you
In Vue.js parent-child relationship is run by
1) passing props from parent to child
2) emitting custom events from child to parent
So, if you need to pass some data from child to parent - use this.$emit to emit a custom event with your data, and listen for this event in parent component with v-on:myevent or #myevent shorthand. The data you pass with event is found in $event variable.
Example: https://jsfiddle.net/wostex/63t082p2/51/
<div id="app">
<myform #newdata="handleData($event)"></myform>
<p>name: {{ user.name }}</p>
<p>age: {{ user.age }}</p>
</div>
new Vue({
el: '#app',
data: {
user: { name: '', age: 0 }
},
methods: {
handleData: function(e) {
[this.user.name, this.user.age] = e;
}
},
components: {
'myform': {
template: `
<div>
<input type="text" v-model="formData.name" placeholder="Your name">
<input type="number" v-model.number="formData.age">
</div>`,
data: function() {
return { formData: { name: '', age: 0 } }
},
watch: {
formData: {
handler: function() {
this.$emit('newdata', [this.formData.name, this.formData.age]);
},
deep: true
}
}
}
}
});
Another way would be to work with advanced things like a Vuex store for ''state management'' but for simple implementations one additional reactive component would work as well.
in src/store/index.js
import { reactive } from 'vue';
export const store = reactive({
some_id : 0,
});
And in a component src/component/SelectComponent.vue
<script setup>
import { store } from "#/store";
</script>
<script>
export default {
name: "SelectComponent",
// rest of the component source here
}
</script>
<template>
<select v-model="store.some_id">
<option v-for="itm in list" :key=itm.id" :value="itm.id">{{ itm.text }}</option>
</select>
</template>
Using the component in src/views/SomeView.vue
<script setup>
import { store } from "#/store";
import SelectComponent from "#/components/SelectComponent"
</script>
<script>
//... use store.some_id in some method
</script>
You can store all your global variables in the store/index.js file and keep reactive. You might want to add watchers to observe the store variable(s).
WARNING: this is discouraged for large, complex Vue applications
NOTE: this is an easy approach for simple state management not requrring Vuex with all the actions and mutations, states and contexts - plumbing.