[英]Create Vue.js object on existing data
我的服务器生成了以下代码:
<div id="app-4" data-server-rendered="true">
<ul>
<li>Article 1 test1</li>
<li>Article 2 test2</li>
</ul>
</div>
现在使用Vue.js,如果数据更改,我想再次生成此代码。 那可能吗 ?
我试图做点什么,但是没有用:
var app4 = new Vue({
el: '#app-4',
props: ["todo"],
template: ' <ul>\n' +
' <li v-for="todo in todos">\n' +
' {{ todo.title }} {{ todo.text }}' +
' </li>\n' +
' </ul>',
data: {
todos: [
{ title: 'Article 3', text:"test1" },
{ title: 'Article 4', text:"test2" },
{ title: 'Article 5', text:"test3" }
]
}
})
从理论上讲,当我放置一个data.todos值与服务器生成的输出中的值不同时,它应该更改。 但这和我的2 li在一起。 如果删除data-server-rendered =“ true”,它将显示我的3 li。
我认为问题是您正在尝试让Vue覆盖包含data-server-rendered
的标签。 您想在其中补充水分。 如果我将el: '#app-4'
设置为el: '#app-4'
(如您所做),则会收到错误消息:
客户端渲染的虚拟DOM树与服务器渲染的内容不匹配。
如果我在ul
设置id="app-5"
并在Vue规范中使用el: '#app-5'
,则不会收到该错误,并且一切正常。
var app4 = new Vue({ el: '#app-5', template: ' <ul>\\n' + ' <li v-for="todo in todos">\\n' + ' {{ todo.title }} {{ todo.text }}' + ' </li>\\n' + ' </ul>', data: { todos: [ { title: 'Article 3', text:"test1" }, { title: 'Article 4', text:"test2" }, { title: 'Article 5', text:"test3" } ] } });
<script src="//unpkg.com/vue@latest/dist/vue.js"></script> <div id="app-4" data-server-rendered="true"> <ul id="app-5"> <li>Article 1 test1</li> <li>Article 2 test2</li> </ul> </div>
您可以在js页面上使用组件声明模板。
Vue.component('todo',{
template:`<ul><slot></slot></ul>`,
});
并在您的html页面上
<todo>
<li v-for="todo in todos">{{todo.title}}</li>
</todo>
我的问题是由于\\ n
我的HTML必须是这样的
<ul id="app-5" data-server-rendered="true"><li>Learn JavaScript test1</li><li>Learn Vue test2</li><li>Build something awesome test3</li></ul>
而我的js:
var app5 = new Vue({
el: '#app-5',
template: '<ul id="app-5"><li v-for="todo in todos">{{ todo.title }} {{ todo.text }}</li></ul>',
data: {
todos: [
{ title: 'Learn JavaScript', text:"test1" },
{ title: 'Learn Vue', text:"test2" },
{ title: 'Build something awesome', text:"test3" },
]
}
})
我想如果我都使用模板进行渲染,那将毫无问题。 这就是我要做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.