I want to use Vue.js to more easily manipulate the DOM but when I initialize a Vue object it rewrites initial data that is generated with backend at first before manipulating.
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 would somehow read already existing markup and preserve it before manipulating via editing $data
. Is this somehow achievable?
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.
vue-template-loader compiles HTML into individual render functions in the respective TypeScript or JavaScript files.
I think this is not possible the way you want to do it. Vue.JS doesn't operate on the DOM directly. It reads the DOM elements, converts them into a render function and replaces the whole Element with the result of the render-function.
You should probably use JQuery to scan your DOM and fill your $data object (and possibly your template-string for Vue) and then initialie your Vue instance with this generated data.
But overall - you should rethink your application logic, because you seem to be doing something very convoluted, which could possibly be solved a lot easier. Whatever generates your DOM-Template could probably also directly render into a JS-variable, or even be accessed with an AJAX call...
If you want to render a fallback approach if the client does not support JS or the CDN for Vue is not available you can use the script-template approach. Define your Vue.JS content in a script-tag, which 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With