vue.js reactivity and data with mixin - javascript

I am trying to set a flag that can be a boolean value true or false based on certain conditions.
// main.js
new Vue({
el: `#app`,
render: h => h(App,{
props:{
todoID: this.dataset.id
}
})
})
my App script
export default {
name: 'App',
props: {
todoID: String,
},
data() {
return {
isDone: false // here is the initial flag
}
},
...
I created a mixin method
import Vue from "vue";
Vue.mixin({
methods: {
isCompleted() {
if (myconditions){
this.isDone = true; // I want to change the flag to true
}
},
},
});
in my template if I do {{isDone}} I always get false, how can I change this to be reactive so it can be changed based on the conditions?
Here is a demo I created: https://codesandbox.io/embed/vigorous-bell-p1itu?fontsize=14&hidenavigation=1&theme=dark

Vue.mixin({
methods: {
isCompleted(myconditions) {
console.log(myconditions);
console.log(typeof myconditions);
return this.isDone = myconditions; // I want to change the flag to true
},
},
});
new Vue({
el: '#vue-app',
data: {
isDone: false
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-app">
<p> result = {{ isCompleted(true) }}</p>
</div>
</body>

I believe this is because I didn't see in your code where this isDone variable is being changed.
I made a demonstration with a function changing this variable through the same method done in your mixin.
example

Related

How to access vanilla class instance stored from one Vue component in a parent component?

I have a parent component with 2 child components that both inherit from the same base component. (This parent component is being created and used in a Vue Storybook). Both SiblingAComponent and SiblingBComponent inherit the same BaseComponent, and instantiate the same inherited data classInstance, which is a vanilla JS class instance from another library. I am trying to access this classInstance from the parent component to pass as data into the second sibling component (in this case, from SiblingAComponent to SiblingBComponent), by using an reference siblingARef. However, I get this error from the storybook compiler:
too much recursion
isArguments#http://localhost:6006/vendors~main.9107ef8d0bc0558399e1.bundle.js:49010:16
keys#http://localhost:6006/vendors~main.9107ef8d0bc0558399e1.bundle.js:49073:28
_traverse#http://localhost:6006/vendors~main.9107ef8d0bc0558399e1.bundle.js:119972:19
_traverse#http://localhost:6006/vendors~main.9107ef8d0bc0558399e1.bundle.js:119974:28
ParentComponent Story:
storiesOf("ParentComponent Story", module)
.addDecorator(
withKnobs({
escapeHTML: false
})
)
.add("Passing data from A to B", () => ({
name: 'ParentComponent',
components: {
SiblingAComponent,
SiblingBComponent,
},
data() {
return {
siblingAData: [....], // array of objects
siblingAOptions: {
axes: {},
height: "50px",
},
siblingBData: [...], // array of objects
siblingBOptions: null,
}
},
mounted() {
const siblingAInstance = this.$refs.siblingARef.classInstance;
const newOptions = {
legend: {
external: {
reference: siblingAInstance,
},
},
};
// this line is where I am getting an error
this.siblingBOptions = legendExternal;
},
template: `
<SiblingAComponent ref="siblingARef" :data="siblingAData" :options="siblingAOptions"/>
<SiblingBComponent v-if="siblingBData" :data="siblingBData" :options="siblingBOptions"/>
`,
}));
SiblingAComponent:
<template>
<div class="sibling-a-component"></div>
</template>
<script>
import { ComponentA } from '#libraryexample/components';
import BaseComponent from './base-component.vue';
export default {
name: 'SiblingAComponent',
extends: BaseComponent,
mounted() {
this.classInstance = new ComponentA(this.$el, {
data: this.data,
options: this.options,
});
},
};
</script>
SiblingBComponent:
<template>
<div class="sibling-b-component"></div>
</template>
<script>
import { ComponentB } from '#libraryexample/components';
import BaseComponent from './base-component.vue';
export default {
name: 'SiblingBComponent',
extends: BaseComponent,
mounted() {
this.classInstance = new ComponentB(this.$el, {
data: this.data,
options: this.options,
});
},
};
</script>
BaseComponent:
<script>
export default {
name: 'BaseComponent',
data() {
return {
classInstance: null,
};
},
props: {
data: { type: [Object, Array], required: true },
options: { type: Object, required: true },
},
};
</script>
Coming from the Angular and React worlds, using a reference to access a Vanilla class instance from another Component is nothing new, even if it's unconventional. I am new to Vue, so I am wondering why would trying to access a class instance fail (works fine for primitive data types) and give me such a weird error? Where is the recursion occurring?

How can I reactively update a value in a component from a store value?

I have two components and a basic store as per the docs here: https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch.
I want to make it so that when I type into an input the value in a different component is updated by using the store.
Basic example here.
App.vue
<template>
<div id="app">
<h1>Store Demo</h1>
<BaseInputText /> Value From Store: {{ test }}
</div>
</template>
<script>
import BaseInputText from "./components/BaseInputText.vue";
import { store } from "../store.js";
export default {
// This should reactively changed as per the input
computed: {
test: function() {
return store.state.test;
}
},
components: {
BaseInputText
}
};
</script>
BaseInput.vue
<template>
<input type="text" class="input" v-model="test" />
</template>
<script>
import { store } from "../store.js";
export default {
data() {
return {
test: store.state.test
};
},
// When the value changes update the store
watch: {
test: function(newValue) {
store.setTest(newValue);
}
}
};
</script>
store.js
export const store = {
debug: true,
state: {
test: "hi"
},
setTest(newValue) {
if (this.debug) console.log("Set the test field with:", newValue);
this.state.test = newValue;
}
};
I want to make it so that when I type a string into the input the test variable in App.vue is updated. I'm trying to understand how the store pattern works. I'm aware of how to use props.
I also have a working copy here: https://codesandbox.io/s/loz79jnoq?fontsize=14
Updated
2.6.0+
To make store reactive use Vue.observable (added in in 2.6.0+)
store.js
import Vue from 'vue'
export const store = Vue.observable({
debug: true,
state: {
test: 'hi'
}
})
BaseInputText.vue
<input type="text" class="input" v-model="state.test">
...
data() {
return {
state: store.state
};
},
before 2.6.0
store.js
import Vue from 'vue'
export const store = new Vue({
data: {
debug: true,
state: {
test: 'hi'
}
}
})
BaseInputText.vue
<input type="text" class="input" v-model="state.test">
...
data() {
return {
state: store.state
};
}
Old answer
From documentation However, the difference is that computed properties are cached based on their reactive dependencies.
The store is not reactive
Change to
App.vue
data() {
return {
state: store.state
};
},
computed: {
test: function() {
return this.state.test;
}
},
It looks bad but I don't see another way to make it work

Sibling component communication not working in vue

I am trying to send this.TC from typing.js to ending-page.js which are sibling components. Emits and event hubs not working. But emit from typing.js to parent works as I want. (There will be only one more call in this app, so i don't want use Vuex if it isnt necessary for this - i want to do it with simple emits ) Here's my code:
Parent:
<template>
<div id = "app">
<typing v-if = "DynamicComponent === 'typing'" />
<ending_page v-else-if = "DynamicComponent === 'ending_page'" />
</div>
</template>
<script>
/* Importing siblings components to parent component */
import typing from './components/typing/index.vue'
import ending_page from './components/ending-page/index.vue'
export default {
name: 'app',
components: {
typing,
ending_page
},
data() {
return {
DynamicComponent: "typing",
};
},
methods: {
updateDynamicComponent: function(evt, data){
this.DynamicComponent = evt;
},
},
};
</script>
typing.js:
import { eventBus } from "../../main";
export default {
name: 'app',
components: {
},
data() {
return {
/* Text what is in input. If you write this.input = "sometext" input text will change (It just works from JS to HTML and from HTML to JS) */
input: "",
/* Object of TypingCore.js */
TC: "somedata",
/* Timer obejct */
timer: null,
is_started: false,
style_preferences: null,
};
},
ICallThisFunctionWhenIWantToEmitSomething: function(evt) {
/* Sending data to ending_page component */
this.$root.$emit('eventname', 'somedata');
/* Calling parent to ChangeDynamicComponent && sending TC.data what will be given to ending_page (I think it looks better with one syntax here) */
this.$emit('myEvent', 'ending_page', this.TC.data);
}
},
};
ending-page.js:
import { eventBus } from "../../main";
export default {
name: 'ending-page',
components: {},
data () {
return {
data: "nothing",
}
},
computed: {
},
props: {
},
methods: {
},
/* I know arrow functions etc but i was trying everyting */
created: function () {
this.$root.$on('eventname', function (data) {
console.log(data)
this.title = data
this.$nextTick()
})
}
}
It is an example of how to share data between siblings components.
Children components emits events to parent. Parent components send data to children.
So, the parent has the property title shared between the children. When typing emits
the input event the directive v-modelcapture it an set the value on parent.
Ref:
https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components
https://benjaminlistwon.com/blog/data-flow-in-vue-and-vuex/
Vue.component('typing', {
props: {
value: ''
},
template: '<button #click="emit">Click to change</button>',
methods: {
emit() {
this.$emit('input', `changed on ${Date.now()}`);
}
}
});
Vue.component('ending-page', {
props: {
title: ''
},
template: '<div>{{ title }}</div>',
});
var app = new Vue({
el: '#app',
data() {
return {
title: 'unchanged',
};
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<typing v-model="title"></typing>
<ending-page :title="title"></ending-page>
</div>
One can try communication using vuex,
the data you want to share make it on this.$store.state or if recalling for functions use mutation(sync functions) and actions(async functions)
https://vuex.vuejs.org/
I like what Jeffrey Way suggested once, just create a global events object (which accidentally can be another Vue instance) and then use that as an event bus for any global communication.
window.eventBus = new Vue();
// in components that emit:
eventBus.$emit('event', data);
// in components that listen
eventBus.$on('event');

Vue.js - One-way data binding updating parent from child

Given that a colon indicates one-way-data-binding in VueJS2, I would like to understand why in this example, the child is able to update the array that was declared in the parent and passed to the child via prop (one-way).
https://jsfiddle.net/ecgxykrt/
<script src="https://unpkg.com/vue"></script>
<div id="app">
<span>Parent value: {{ dataTest }}</span>
<test :datatest="dataTest" />
</div>
var test = {
props: ['datatest'],
mounted: function() {
this.datatest.push(10)
},
render: function() {}
}
new Vue({
el: '#app',
components: {
'test': test
},
data: function() {
return {
dataTest: []
}
}
})
Thanks in advance!
Vue prevents you from assigning to a prop. It does not prevent you from calling a prop's methods or modifying its elements or members, any of which can change the contents of the object. None of these things changes the value of the prop itself, which is a reference to an underlying structure.
A related issue is the fact that Vue cannot detect changes to Array elements or additions/deletions of Object members.
More here.
If you wanted to, you could avoid this by creating a shallow copy and assigning it to a new data item in the child.
https://jsfiddle.net/6xxba1fz/
var test = {
props: ['test'],
data: function() {
return {
myTest: this.test.slice()
}
},
mounted: function() {
this.myTest.push(10)
},
render: function() {}
}
new Vue({
el: '#app',
components: {
'test': test
},
data: function() {
return {
dataTest: []
}
}
})
Please avoid to using the some name for key and value
:datatest="dataTest" Wrong Way
:data-test="dataTest" Better Way (use Kabab case)
HTML
<div id="app">
<span>Parent value: {{ dataTest }}</span>
<test :data-test="dataTest" />
</div>
JS
var test = {
props: {
dataTest:{
type:Number
}
},
mounted: function() {
this.datatest.push(10)
},
render: function() {}
}
new Vue({
el: '#app',
components: {
'test': test
},
data: function() {
return {
dataTest: []
}
}
})
Result:
Parent value: []

Access a component and trigger click event from App.vue component

In my template I have one click event
<span v-on:click="showGalery()">
And I am using one method for it
export default {
name: 'osaka',
data: function () {
return {
galery: false,
}
},
methods: {
showGalery () {
this.galery = true
}
}
}
Is it possible to trigger this method from App.vue template where is my nav and router links is located?
I am using vue-webpack template.
I have components, router.js, App.js and main.js structure.
Remember Vue has a one way data flow, so if you want to set something on the component you can simply pass a prop and use a watcher to trigger the change:
Vue.component('gallery', {
template: `<div v-show="gallery">Gallery</div>`,
props: {
show: {
type: Boolean,
default: false
}
},
created() {
this.gallery = this.show;
},
watch: {
show(val) {
this.gallery = val;
}
},
data() {
return {
gallery: false
}
}
});
Then in the parent you would have:
new Vue({
el: '#app',
data: {
showGallery: false
}
});
And use the following markup:
<gallery :show="showGallery"></gallery>
See this JSFiddle: https://jsfiddle.net/yx1uq370/
Incidentally, if you just want to show hide the entire component, then you can just use v-show on the component itself which
Vue.component('gallery', {
template: `<div>Gallery</div>`
});
new Vue({
el: '#app',
data: {
showGallery: false
}
});
Then your markup:
<gallery v-show="showGallery"></gallery>
And here's the fiddle for that: https://jsfiddle.net/gfr9kmub/
One final thing, are you sure that you really need to trigger this from your nav? I would assume that your nav would display the views and the views themselves would take care of this type of state management. Otherwise you may want to look at vuex to handle this situation

Categories