Output data from one Vue.js instance into another - javascript

I have a pretty big page with lots of stuff going on. So i have 2 Vue instances for 2 parts of the page. How can i bind data from one Vue instance into another?
This example should show what i am trying to do. (it's not working that way)
<div class="app1">...</div>
...
<div class="app2">{{app1.$data.msg}}</div>
var app1 = new Vue({
el: '.app1',
data: {msg: "test"}
});
var app2 = new Vue({
el: '.app2'
});

In advance, I know this isn't the question you are asking, but I don't know why you need two instances of Vue. Why not just bind Vue to the body and treat both the Vue instances as components. It might be difficult to do what you are trying to do, because it was not intended. Maybe it was, I don't know. I have set Vue up on the body and I haven't seen a performance hit. Here is a JSBin.
HTML
<div class="container">
<div id="app1">
<h1>{{ msg }}</h1>
<input type="text" v-model="msg" class="form-control"/>
</div>
<div id="app2">
<h1>{{ msg }}</h1>
<input type="text" v-model="msg" class="form-control"/>
</div>
</div>
JavaScript
var VueComponent1 = Vue.extend({
template: '#app1',
data: function(){
return {
msg: ""
}
}
});
var VueComponent2 = Vue.extend({
template: '#app2',
data: function(){
return {
msg: ""
}
}
});
var app1 = Vue.component('app1', VueComponent1);
var app2 = Vue.component('app2', VueComponent2);
var app = new Vue({
el: 'body',
data: { msg: 'Everybody loves Vue.' }
});
If you are looking for a better way to separate you code, you might want to check out this Vue with Browserify example.
Laracasts has a free series on Vue which has been pretty informative as well.

I am still looking for the best solution. The following feels a bit hacky but it works.
You can use the watch option to listen for the change of an expression and trigger a function. In this function you can update the desired data of another Vue instance. In you example we would do this:
var app1 = new Vue({
el: '.app1',
data: {msg: 'test'},
watch: {
'msg': function() { app2.msg = this.msg; }
}
});
var app2 = new Vue({
el: '.app2',
data: { msg: app1.$data.msg },
watch: {
'msg': function() { app1.msg = this.msg; }
}
});
You can see this at work in this jsbin.
Moreover, I am wondering if you even need to do this. If this was a real-life-situation there could be better ways to handle this avoiding this hacky solution.

Related

[Vue warn]: Property or method "hp" is not defined on the instance but referenced during render

I have the following code:
var example1;
var hp = ["p"];
document.addEventListener("DOMContentLoaded", function(event) {
hp = ["x"];
example1 = new Vue({
el: '#example-1', //yes i have an element with #example-1 (not relevant here)
data: {
iLoveMyself: window.hp
},
watch: {
iLoveMyself: {
deep: true,
immediate: true,
handler (val, oldVal) {
console.log("yeeeh")
}
}
}
})
});
I tried many things (that's why my code ^ is so damn ugly) but i keep this console.error:
vue.js:634 [Vue warn]: Property or method "hp" 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. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
If i look up the value in the chrome plugin for VueJs the the data set is as followed:
iLoveMyself:Array[1]
0:"x"
All good so far but when trying to update hp like:
hp.push("y");
hp.pop();
hp = "ZEBRA";
I get no response what so ever.
What is that i don't understand ?
Gratitude in advance!
Edit:
So after all i start to gather to pieces, my html is important after all :/
<div id="example-1">
<div v-for="ev in hp" :key="ev.beavus">
{{ ev.beavus }}
</div>
</div>
Here is a more idiomatically Vue implementation of what you posted in the question:
new Vue({
el: '#example-1',
data: {
iLoveMyself: [{beavus: "x"}]
},
watch: {
iLoveMyself: {
deep: true,
immediate: true,
handler (val, oldVal) {
console.log("yeeeh")
}
}
},
methods: {
add () {
this.iLoveMyself.push({beavus: Math.random()})
}
}
});
<script src="https://unpkg.com/vue#2.6.11/dist/vue.js"></script>
<div id="example-1">
<div v-for="ev in iLoveMyself" :key="ev.beavus">
{{ ev.beavus }}
</div>
<button #click="add">Add</button>
</div>
I've got rid of the global variables, there's now just an instance property called iLoveMyself that holds the array. Pushing extra data to the array triggers both the watch and updates the DOM with the new data.
You should do :
<div id="example-1">
<div v-for="ev in iLoveMyself" :key="ev.beavus">
{{ ev.beavus }}
</div>
</div>

Pass variable from within script tags to Vue instance

In my Drupal 7 site's html I have this
<script>$L = $L.wait(function() {
(function($) {
Drupal.behaviors.related_products = {
attach: function (context, settings) {
artiklar = Drupal.settings.related_products.artiklar;
console.log(artiklar);
}
};
})(jQuery);
});</script>
In the variable artiklar above I have some data that I have passed from the server side using Drupal behaviors. Now, on the client side I need to access the variable artiklar in a Vue component, like so:
Vue.component('artikel-lista', {
template:`
<ul>
<artikel v-for="artikel in artiklar">{{ artikel.title }} Pris: {{artikel.price}} <a :href="artikel.link" class="button tiny" target="_blank">Läs mer</a></artikel>
</ul>
`,
data(){
return {
artiklar: "",
};
},
mounted: function(){
this.artiklar = artiklar // how can I access the variable "artiklar" here
},
});
The data in the variable consists of an array of items, that I need in my Vue component. But how can I pass the variable from within the script tags to the Vue instance, that lives in a separate file, inserted just before the ending body tag. Anyone?
If you have data in the globally visible Drupal.settings.related_products.artiklar object then you can refer to it practically the same way in Vue.js. or if you must use this function, assign data to global scope window.*.
new Vue({
template: `<div>{{foo}} / {{bar}}</div>`,
data() {
return {
foo: Drupal.settings.related_products.artiklar,
bar: window.artiklarData
};
}
}).$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">Vue App</div>
<script>
// simulate global variable
var Drupal = {
settings: {
related_products: {
artiklar: ['fus', 'ro', 'dah']
}
}
};
(function() {
window.artiklarData = Drupal.settings.related_products.artiklar;
})();
</script>
If you assign the value to Drupal.settings.related_products.artiklar after creating the Vue object, you can try to use the solutions described in the documentation, e.g.
const vm = new Vue({
template: `<div>{{foobar}}</div>`,
data() {
return {
foobar: 'Initial value'
};
}
}).$mount("#app");
setTimeout(() => {
// simulate global variable
var Drupal = {
settings: {
related_products: {
artiklar: 'Changed value'
}
}
};
(function() {
vm.foobar = Drupal.settings.related_products.artiklar;
})();
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">Vue App</div>
Maybe you could use RxJS but I don't have enough knowledge to tell if it's true and give an example.
Just in case anyone else is struggling with the same thing, I post this answer to my own question (I accidentally posted the question with the wrong account). In the end it turns out that the answer from Gander was correct and that I could access the variable directly in the Vue component, w/o first stashing it an a global variable. The viewed result was kind of weird though and after some trialling I found out that I had to parse the result with JSON.parse(). This is the working code now:
Vue.component('artikel-lista', {
template:`
<ul>
<artikel v-for="artikel in artiklar">{{ artikel.title }} Pris: {{artikel.price}} <a :href="artikel.link" class="button tiny" target="_blank">Läs mer</a></artikel>
</ul>
`,
data(){
return{
artiklar:""
}
},
mounted:function(){
this.artiklar = JSON.parse(Drupal.settings.related_products.artiklar);
console.log(this.artiklar);
}
});

Vue2 watch Set Not Working

I have a simple Vue app that is supposed to add a number to a Set when you click the "Add to Set" button --
https://codepen.io/jerryji/pen/mKqNvm?editors=1011
<div id="app">
<input type="number" placeholder="enter a number" v-model="n">
<button type="button" #click.prevent="addToSet()">Add to Set</button>
</div>
new Vue({
el: "#app",
data: {
n: null,
nSet: new Set()
},
methods: {
addToSet: function() {
this.nSet.add(this.n);
console.log(this.n + ' added to Set');
}
},
watch: {
nSet: function (newVal, oldVal) {
console.log(newVal);
}
}
});
Why is nothing logged in the console by the watch?
Saving and re Setting the Set using the .values() method on Set worked for me and i didn't have to use $forceUpdate
Using $forceUpdate might be the more sensible way to go though. In some use cases in the past i have found forcing components to update to be problematic.
new Vue({
el: "#app",
data: {
n: null,
nSet: new Set()
},
methods: {
addToSet: function() {
let set = this.nSet;
let newSet = set.add(this.n)
this.nSet = new Set(newSet.values())
}
},
watch: {
nSet: function (newVal, oldVal) {
console.log('newVal', ...newVal);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<input type="number" placeholder="enter a number" v-model="n">
<button type="button" #click.prevent="addToSet()">Add to Set</button>
<p>n = {{ n }}</p>
</div>
Vue adds special handling for Arrays, but not for Sets. As a result, Vue doesn't automatically detect changes to Set membership. You can force an update, though
this.nSet.add(this.n);
this.$forceUpdate();
It's because Vue doesn't support Set, Map, WeakSet and WeakMap. And it's because browsers didn't support these structures well. Especially WeakMap. But... They decided to support these structures. Maybe in version 3 - when they decide to drop support for older browsers. So, for now use an object, add properties with Vue.$set() and watch for changes with deep: true.

How to temporize the analysis of an <input> field?

I would like to analyze the content of an <input> field when there is no user activity.
I will take below a simple example (counting the number of characters) but the actual analysis if very expensive so I would like to do it in batches, when there is some inactivity of the user instead of doing it at every change of the bound variable.
The code for the straightforward analysis could be
var app = new Vue({
el: '#root',
data: {
message: ''
},
computed: {
// a computed getter
len: function() {
// `this` points to the vm instance
return this.message.length
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script>
<div id="root">
<input v-model="message">Length: <span>{{len}}</span>
</div>
My problem is that function() is called at each change of message. Is there a built-in mechanism to throttle the query, or a typical approach to such a problem in JS?
That works the way it is supposed to. As it is said in the docs:
It will update any bindings that depend on computed property when the original data changes
But there's a way to do it:
var app = new Vue({
el: '#root',
data: {
message: '',
messageLength: 0
},
methods: {
len: _.debounce(
function() {
this.messageLength = this.message.length
},
300 // time
)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script>
<script src="https://unpkg.com/underscore#1.8.3"></script> <!-- undescore import -->
<div id="root">
<input v-model="message" v-on:keyup="len">Length: <span>{{ messageLength }}</span>
</div>
Full example: https://v2.vuejs.org/v2/guide/computed.html#Watchers
p.s. A comment about computed being sync from the vue's author: https://forum-archive.vuejs.org/topic/118/throttle-computed-properties/3
p.p.s Classics article about difference between debounce and throttle.

Ember bindings firing when not wanted, and not firing when required

Hey I'm having two different issues in my ember app, both of which involve bindings.
First, I have a binding firing when I don't want it to. Basically what I'm trying to achieve (I'm building a survey creator front-end app) is that when any text is entered into the 'name' field of a question, I want to add a new question object, which will render out another blank question at the end of the list of questions that the user is adding. This has the effect of there always being a new question, so an add question button is not required. The binding is working, and a new object is being added: however, since the binding is from the newest question object, the binding is triggered again when the new object is created, which in turn creates a new object, which triggers the binding again....which obviously eventually crashes the browser. I've tried using the Ember._suspendObserver function, but there isn't a lot of documentation on this, and I think I'm using it wrong - anyhow it isn't suspending the observer or pausing the binding. The observer in the code is around line 27 (contentsNameObserver)
The other issue I'm having -- I have a selection drop down box which selects what type of question the user wants (single answer, multi-choice, etc.) but the binding between the select box and the {{#each}} helper which renders the kind of question isn't triggering. I'm using the Ember.Select view helper, so there shouldn't be any issues with using get/set to fire the binding. I'm using a computed property to return an array of fields for the question type based on the value of the question type id. The computed property is in line 13 (App.SurveyContent.types), and the template templates/step3. Quick heads up that this app may be extended for more than surveys, hence 'questions' are often referred to in the code as 'content'.
I'm pretty new to ember (this is my first real app) so my code most likely has a lot of issues outside of these problems...so any comments on how I've structured my app would be hugely appreciated as well!
Javascript ember app:
App = Ember.Application.create({
rootElement: '#emberContainer'
});
App.SurveyContent = Ember.Object.extend({
name: "",
content_type: 1,
content_pos: 1,
hash: Em.A([]),
types: function() {
alert("redraw");
return App.ContentTypes[this.content_type-1].hash;
}.property()
});
App.Surveys = Ember.Object.create({
name: null,
start: $.datepicker.formatDate('mm/dd/yy' , new Date()),
end: $.datepicker.formatDate('mm/dd/yy' , new Date()),
themeID: 0,
contents: [App.SurveyContent.create()], //Pushing an instance of App.SurveyContent onto this
contentsNameObserver: function() {
context = this;
console.log("entering");
Em._suspendObserver(App.Surveys, "contents.lastObject.name", false, false, function() {
console.log("suspend handler");
context.contents.pushObject(App.SurveyContent.create());
})
}.observes("contents.lastObject.name")
});
App.ContentTypes = [
Ember.Object.create({name: 'Text question', id:1, hash: [Ember.Object.create({name: 'Question', help: 'Enter the question here', type: 'text'})]}),
Ember.Object.create({name: 'Multichoice question', id:2, hash: [Ember.Object.create({name: 'Question', help: 'Enter the question here', type: 'text'}),
Ember.Object.create({name: 'Answer', help: 'Enter possible answers here', type: 'text', multiple: true})]})
];
App.ViewTypeConvention = Ember.Mixin.create({
viewType: function() {
console.log(this);
return Em.get("Ember.TextField");
}.property().cacheable()
});
App.CRMData = Ember.Object.extend();
App.CRMData.reopenClass ({
crm_data: [],
org_data: [],
org_display_data: [],
loadData: function() {
context = this;
context.crm_data = [];
$.getJSON ("ajax/crm_data", function(data) {
data.forEach(function(crm) {
context.crm_data.pushObject(App.CRMData.create({id: crm.crm_id, name: crm.crm_name}));
crm.orgs.forEach(function(org) {
context.org_data.pushObject(App.CRMData.create({id: org.org_id, name: org.org_name, crm_id: crm.crm_id}));
}, context)
}, context)
context.updateOrganisations(5);
});
return this.crm_data;
},
updateOrganisations: function(crm_id) {
context = this;
this.org_display_data.clear();
console.log("clearing the buffer")
console.log(this.org_display_data)
context.org_data.forEach(function(org) {
if(org.crm_id == crm_id) {
context.org_display_data.pushObject(App.CRMData.create({id: org.id, name: org.name}));
}
}, context)
}
});
App.DateField = Ember.TextField.extend({
attributeBindings: ['id', 'class']
});
App.CRMSelect = Ember.Select.extend({
attributeBindings: ['id'],
change: function(evt) {
console.log(evt)
App.CRMData.updateOrganisations($('#crm').val())
}
});
App.ApplicationController = Ember.Controller.extend();
App.Step1Controller = Ember.ArrayController.extend({});
App.Step2Controller = Ember.ArrayController.extend({});
App.Step2Controller = Ember.ArrayController.extend({});
App.ApplicationView = Ember.View.extend({
templateName: 'app'
});
App.Step0View = Ember.View.extend ({
templateName: 'templates/step0'
});
App.Step1View = Ember.View.extend ({
templateName: 'templates/step1'
});
App.Step2View = Ember.View.extend ({
templateName: 'templates/step2',
didInsertElement: function() {
$( ".jquery-ui-datepicker" ).datepicker();
}
});
App.Step3View = Ember.View.extend ({
templateName: 'templates/step3',
});
App.Router = Em.Router.extend ({
enableLogging: true,
root: Em.Route.extend ({
showstep1: Ember.Route.transitionTo('step1'),
showstep2: Ember.Route.transitionTo('step2'),
showstep3: Ember.Route.transitionTo('step3'),
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router){
router.get('applicationController').connectOutlet( 'step0');
}
}),
step1: Ember.Route.extend ({
route: 'step1',
connectOutlets: function(router){
router.get('applicationController').connectOutlet( 'step1', App.CRMData.loadData());
}
}),
step2: Ember.Route.extend ({
route: 'step2',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('step2')
},
}),
step3: Ember.Route.extend ({
route: 'step3',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('step3')
},
})
})
});
Ember.LOG_BINDINGS=true;
App.LOG_BINDINGS = true;
App.ContentTypes.forEach(function(object) {
object.hash.forEach(function(hash) {
hash.reopen(App.ViewTypeConvention);
}, this);
}, this);
Html templates (I've got these in haml, so this is just a representation of the important ones)
<script type="text/x-handlebars" data-template-name="app">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="templates/step3">
<h1> Add content to {{App.Surveys.name}} </h1>
<br>
<div id = "accordion2" class = "accordion">
{{#each content in App.Surveys.contents}}
<div class="accordion-group">
<div class = "accordion-heading">
<a class = "accordion-toggle" data-parent = "#accordion2" data-toggle = "collapse" href = "#collapseOne">
{{content.name}}
</a>
</div>
<div id = "collapseOne" class = "accordion-body collapse in">
{{view Ember.TextField valueBinding="content.name" class="txtName"}}
<form class = "form-horizontal">
<div class = "accordion-inner">
<div class = "control-group">
<label class = "control-label" for ="organisation">
Content Type
<div class = "controls">
{{view Ember.Select contentBinding="App.ContentTypes" optionValuePath="content.id" optionLabelPath="content.name" valueBinding="content.content_type"}}
</div>
</div>
</div>
{{#each item in content.types }}
<div class = "control-group" >
<label class = "control-label" for = "organisation">
{{item.name}}
<div class = "controls">
{{view item.viewType }}
</div>
{{/each}}
</div>
</form>
</div>
{{/each}}
</div>
</div>
<br>
<div class = "btn" {:_action => 'showstep3'}> Next Step > </div>
</script>
I've solved the first issue, although I didn't get the suspendObserver property working I used an if statement to check the previous element, removing the infinite loop.
contentsNameObserver: function() {
context = this;
if(this.get('contents.lastObject').name) {
context.contents.pushObject(App.SurveyContent.create());
}
}.observes("contents.lastObject.name")
Any comments on how to get the _suspendObserver handler working would be appreciated though, it is something that should work but I'm doing something wrong
I've created a stripped down jsfiddle at http://jsfiddle.net/reubenposthuma/sHPv4/
It is set up to go straight to the problem step, step 3, so that I don't need to include all the previous templates.
I'm still stuck on the issue of the binding not firing though. The behaviour I'm expecting is that when the 'Content Type' dropdown box is changed, the text box underneath should change, it should re-render with two text boxes.
I realise this is an old question, but there is no documenation and precious little information I could find searching either, hence sharing what I found worked here.
What I found worked was to call Ember._suspendObserver as follows:
somePropertyDidChange: function(key) {
var that = this;
Ember._suspendObserver(this, key, null,
'somePropertyDidChange', function() {
// do stuff which would normally cause feedback loops
that.set('some.property', 'immune to feedback');
});
}.observes('some.property');
You can also use the multiple observer variant as follows:
somePropertiesDidChange: function(key) {
var that = this;
Ember._suspendObservers(this, ['some.property', 'another.property'],
null, 'somePropertiesDidChange', function() {
// do stuff which would normally cause feedback loops
that.set('some.property', 'immune to feedback');
that.set('another.property', 'also immune to feedback');
});
}.observes('some.property', 'another.property');
In my exact use case I actually called Ember._suspendObservers from an Ember.run.once() function which was setup by the observer since I wanted to make sure a number of dependant properties had settled before doing calculations which in turn would mutate some of those properties.

Categories