Is there a way to initialize a Vue object that preserves the original HTML

I want to use Vue.js for easier control of the DOM, but when I initialize the Vue object, it overwrites the original data that is first generated using the backend before manipulating it.

For example, I have this markup:

<ul id="list"> <li v-repeat="elements" v-text="content">a</li> <li v-repeat="elements" v-text="content">b</li> <li v-repeat="elements" v-text="content">c</li> </ul> 

And then I want to use new Vue({ el: '#list' }) so that it somehow new Vue({ el: '#list' }) existing markup and saves it before manipulating it using $data editing. Is this somehow achievable?

+6
source share
2 answers

I think it is not possible how you want to do it. Vue.JS does not work directly with the DOM. It reads the DOM elements, converts them to a rendering function, and replaces the entire element with the result of the rendering.

You should probably use jQuery to scan the DOM and populate your data object (and possibly your template string for Vue), and then initialize the Vue instance using this generated data.

But in general - you have to rethink your applied logic, because you seem to be doing something very confusing, which could be solved much easier. Regardless of what your DOM-Template generates, it may also be possible to directly convert to a JS variable, or even access it with an AJAX call ...

If you want to display the fallback approach, if the client does not support JS or CDN for Vue, you cannot use the script -template approach. Define your Vue.JS content in a script -tag that will replace the original DOM when Vue is ready.

Example:

 function loadVue() { new Vue({ data: { values: [ 'aaa','bbb','ccc' ] }, template: '#list-template', el: '#list' }) } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script> <ul id="list"> <li>a</li> <li>b</li> <li>c</li> <button onclick="loadVue()">Load Vue.JS</button> </ul> <script type="text/x-template" id="list-template"> <ul id="list"> <li v-for="v in values">{{v}}</li> </ul> </script> 
0
source

There is no reason why you cannot use a combination of existing elements and v-repeat like this

 new Vue({ el: '#list', data: { elements: [{ content: "d (v-repeat)" }, { content: "e (v-repeat)" }, { content: "f (v-repeat)" }] } }); 
 <script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.11.4/vue.min.js"></script> <ul id="list"> <li>a</li> <li>b</li> <li>c</li> <li v-repeat="elements" v-text="content">c</li> </ul> 
You just don't put v-repeat on elements already present.
0
source

Source: https://habr.com/ru/post/980048/


All Articles