Use Knockout.js on the same page as Vue.js - javascript

Hi I have an existing project which uses alot of knockoutjs.
Im attempting to add vuejs to the project and slowly move everything over to vuejs in time.
Ive added vue to a wrapper element which contains the whole page and created a single vue component.
My aim is to use that component anywhere on the page but not break my knockout code.
The problem im having is my knockout bindings are not being defined when I apply the vue el tag to the main element that wraps the page and the ko.applyBindings scripts. (vue elements work ok but all ko scripts throw an error )
I am using complied templates and the vue-cli with webpack-simple.
Im pretty new to vuejs but I think this is happening because vue is trying to parse the knockoutjs code inside the page html
console error:
ReferenceError: Unable to process binding "slideVisible: function(){return !isShowBillingForm() }"
Message: isShowBillingForm is not defined
at slideVisible (eval at parseBindingsString (knockout-3.3.0.js:61), <anonymous>:3:65)
at init (slidevisible.js:15)
at knockout-3.3.0.js:65
at Object.u (knockout-3.3.0.js:35)
at knockout-3.3.0.js:65
at Object.o (knockout-3.3.0.js:10)
at g (knockout-3.3.0.js:65)
at h (knockout-3.3.0.js:63)
at k (knockout-3.3.0.js:63)
at h (knockout-3.3.0.js:63)
If anyone could help me that would be amazing
(Ive also added the vue cdn to the header and added in vue markup into the page directly and their are no conflicts) so I guess its something to do with the compiled templates?

I've added Vue to a wrapper element which contains the whole page and created a single Vue component.
I believe that's the issue. When migrating to VueJS from legacy Knockout you will have to pick and choose where you want to use Vue.
The way Vue parses the DOM is very different compared to Knockout. It uses a concept of virtual DOM, so the final DOM output is only valid HTML and no framework specific markup. That inherently will break any KO code bound to it.
So the approach I'd recommend is finding pieces of the app you want to convert to Vue and then instantiate Vue inside a Knockout VM (or with plain JS) like this:
import Vue from 'vue';
import MyVueComponent from 'libs/components/my-component.vue';
const propsData = {my: props};
const myComponent = Vue.extend(MyVueComponent);
new myComponent({el: '#some_element', propsData: propsData})
Also important, make sure you tell KO not to process #some_element that Vue is bound to by using the stopBinding handler as described here.
Hope that helps!

Related

Vue3 documentation example codeblocks are strange

All throughout the Vue 3's documentation, they do the following when showing example code in a component:
Vue.createApp({})
I've never had to do this though, I simply use
<script>
export default {
name: 'example-component-xd'
}
</script>
What am I missing here? I just started learning Vue 3, and I haven't learnt any other versions of Vue before. This question is more just a curiosity I have, as it doesn't impact my ability to understand the documentation, but I thought that it may have something to do with the history of Vue, ES6 or best practices etc. Here is another example:
In Vue 3, Vue.createApp({}) replaces new Vue({}) from Vue 2. This line of code is typically in your entry file, where you mount the app (not in your component files).
The code in the <script> tag you showed is for single file components, and you can continue using that style. Never would you use Vue.createApp() or new Vue() in those single file components.
You can checkout an example Vue 3 app that shows Vue.createApp() in src/main.js, while the single file components in src/components use the Options API that you're also using.

How to serve Vue data from Django backend?

So I am trying to use Vue & Django with django-webpack-loader (not DRF), but I'm just getting stuck whenever I try to actually feed Vue data. I am just trying to convert a static Django template to a (.vue) Vue template but I'm not sure how Vue is meant to handle that data?
I'm under the impression that you do something along the lines of this in the script tags:
new Vue ({
data: function () {
game: {{game}}
}
});
And then reference this with {{game.title}} etc in the main html of the Vue template, using Django {% verbatim %} tags so they don't interfere right?
But this just doesn't do anything, Django doesn't give Vue anything and I just get error 'game:' is defined but never used and error 'game' is not defined. I'm just not sure where to go from here and I just need some sort of help...
If I understand correctly that you're trying to have Django directly serve *.vue Single File Components (SFC), then I don't know of anyway that could work. These files will need to be separate from Django so that Vue/webpack can build them into JS.
But there is another way to integrate Django Templates with Vue SFCs. I (humbly) recommend reading my series of articles starting with Vue + Django — Best of Both Frontends. This will walk you through all the steps to do so, freely mixing Django Templates and Vue SFC wherever/whenever you deem appropriate.
There's a companion repo with a ready made Django+Vue starter app.
Otherwise, if I've misunderstood your intention, please clarify so we can better answer.

Using existing cljs components in a React project?

https://www.reddit.com/r/Clojure/comments/4el0xi/how_to_use_an_existing_reactjs_component_with/
There is this existing post about using existing ReactJS components in a CLJS/Reagent project. I'm looking to do the opposite. I have a bunch of CLJS components and would like to compile them into a ui library of some sort so that they can be used by React developers. That is, if I have a button CLJS component, I would like to be able to render that Button using < Button /> or mylib.Button(_) etc.. in a React/js app file.
I have read this - https://shadow-cljs.github.io/docs/UsersGuide.html#target-node-library - extensively but it's not quite working out. I've been using ":target :node-library" and I can get simple functions (that return strings/numbers, for example) to compile and work in my app, etc.. but it doesn't work for entire components. For example, my cljs button component takes in :
defn button [props & children]
but when I try to pass in these parameters (I call {lib.button({}, {})} in my App.js file), I get errors like "No protocol method IMap.-dissoc defined", because I'm trying to pass JS objects into CLJS-only functions, I believe. Not sure how to resolve this..
I can explain more on this if it would help clarify. It would also be super helpful if anyone had a reference demo project or any resources they could link me to.
I only have a few suggestions:
You can try to build a new sample project to consume your library with lein new figwheel myproject and use JavaScript interop to move one step at a time closer to the native JS way of using your library.
You can create an interface namespace that can consume JS objects and wrap these into Clojure data structures to sort out the protocol errors you're seeing, eg. functions that take a props parameter and pass down (js->clj props) to the rest of the code underneath.
For the authoritative source, check the Reagent docs, especially this: http://reagent-project.github.io/docs/master/InteropWithReact.html#creating-react-components-from-reagent-components

AngularJS Directive into React App

We are looking at writing a new app using React but will need some existing Angular Directive that are specific for our business, for example a modified Angular Date Picker for example. There are many components so we won't be able to rewrite them all.
I am wondering if anyone has experience or knows the effort or feasibility of this?
The only article I've managed to find on this so far has been. Most resources I find mention going the other way from an Angular App with added React. http://softeng.oicr.on.ca/chang_wang/2017/04/17/Using-AngularJS-components-directives-in-React/
There's a library called angular2react that makes possible reuse angularjs code inside react components. You can see if it fits your needs. :)
I have written a simple demo app showcasing how to achieve it: react-angularjs-bridge
The basic steps are as follows:
Create a react component that is going to host the angular component in the DOM. This component should always render a simple html element (eg. a HTMLDivElement) so that react does not get confused when reconciling the virtual DOM with the real DOM.
After the react component was mounted componentDidMount, create a shadow root under the rendered HTMLDivElement and initialise the angular application under it. This will ensure that the angularJS component is encapsulated and is not affected by the react application and vice-versa
Click here for a demo. Check how the react application styles do not impact the styles of the angular component.
Independently of Angular, ref is a way to go: it gives to access to an underlying DOM node and the ability to manipulate the DOM inside that node in any way you like, including AngularJS. Your changes will stay - at least until react clears the component altogether.
You can create a ref in react by
<divOrAnyOtherDom ref={((el) => {this._elem=el;}).bind(this)}></...
(for the full description and alternate ways to the same end see here: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs)
Anyway, as you now have a DOM node, you can start working with it, i.e. adding angular to the mix inside componentDidMount. Sadly, this is not really obvious - here's a way that has worked for me in the past (moduleName needs to be a module you have put in place already with your logic):
let baseElement = angular.element(this._elem);
let templateElement = angular.element(templateSource);
angular.injector([ 'ng', moduleName ]).invoke(function($compile, $rootScope) {
let cmp = $compile(templateElement);
scpe = $rootScope.$new(false);
scpe.varname = whateverYouHave; # point is: you can set scope variables
cmp(scpe);
baseElement.append(templateElement);
scpe.$digest();
});
Now you have angular inside the DOM node react gave you.
(I've taken this from a slightly different integration: Vaadin to AngularJS, but the principle is the same: Vaadin, just like react, gives you a DOM node. When you're interested in the full code: https://github.com/akquinet/vaangular/blob/master/vaangular/src/main/resources/de/akquinet/engineering/vaadin/vaangular/angular/NgTemplate.js)
Plus: For any callbacks from the angular component, you'll likely have to use setState et al.

[Vue warn]: Unknown custom element: <testimonial-photo-inner>

I have just installed VueJS on my website and I'm getting tonnes of console errors like the one above. I am not trying to create any Vue components (yet) but my website does contain a number of custom HTML tags.
Does Vue treat any custom HTML tage (e.g. not one in the HTML spec) as something it needs to compile and will it always complain about tags it doesn't recognise?
Is it possible to switch theses warning off?
Please note: This is not a duplicate of Vue js unknown custom element
The user there is actually trying to create a Vue component.
You can use the ignoreElements configuration parameter to have Vue ignore elements that it should not touch.
So in your code you would likely want to add:
Vue.config.ignoredElements = [
'testimonial-photo-inner'
]
And include any other tags you might be using that you do not want Vue to touch.

Categories

Resources