简体   繁体   中英

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM