我使用Javascript创建了HTML元素。当我尝试将代码转换为VueJS时,页面加载时不会创建元素。
HTML
<div id="chat" class="chat-size col-centered margin-btm-50"></div>
VueJS
var chatSample = [
{name:"Julia", message: "Hi"},
{name:"John", message: "Hi"},
{name:"Julia", message: "Bye"}
];
chatSample.forEach(function (obj, i) {
var rowItem = document.createElement('div')
var chatItem = document.createElement('div')
var chatName = document.createElement('div')
var msg = document.createTextNode(obj.message)
var name = document.createTextNode(obj.name)
rowItem.className = 'chat-row margin-chat none'
if (i === chatSample.length - 1) {
rowItem.id = 'last'
}
if (obj.name === 'Police') {
chatItem.className = 'chat-right'
chatName.className = 'name bold text-right padding-chat-right'
} else {
chatItem.className = 'chat-left'
chatName.className = 'name text-left padding-chat-left'
}
chatItem.innerHTML = msg.textContent
chatName.innerHTML = name.textContent
var chat = document.querySelector('#chat');
rowItem.appendChild(chatName);
rowItem.appendChild(chatItem);
});
答案 0 :(得分:0)
Vue使用声明性渲染来显示数据。它有一个非常简单的模板系统,我建议你阅读这个 - https://vuejs.org/v2/guide/
此链接可帮助您呈现列表 - https://vuejs.org/v2/guide/list.html
答案 1 :(得分:0)
为什么不按照VueJS方式进行操作。例如
new Vue({
el: '#demo',
data: {
chatSample: [{
'name': '<b>Chuan</b> | Male | 30 | Subang Jaya',
'message': 'Who is there?'
},
{
'name': 'Police',
'message': 'Police '
},
{
'name': '<b>Chuan</b> | Male | 30 | Subang Jaya',
'message': 'What do you want?'
},
{
'name': 'Police',
'message': 'We want to talk.'
},
{
'name': '<b>Chuan</b> | Male | 30 | Subang Jaya',
'message': 'How many of you are there?'
},
{
'name': '<b>Chuan</b> | Male | 30 | Subang Jaya',
'message': 'How many of you are there?'
},
{
'name': '<b>Chuan</b> | Male | 30 | Subang Jaya',
'message': 'How many of you are there?'
},
{
'name': 'Police',
'message': 'Two.'
},
{
'name': '<b>Chuan</b> | Male | 30 | Subang Jaya',
'message': 'So talk with each other'
}
]
}
})
&#13;
<div id="demo">
<div class="chat-size col-centered margin-btm-50">
<div class="row chat-row margin-chat none" v-for="(chat, idx) in chatSample" :key="idx">
<div class="name text-left padding-chat-left" v-html="chat.name"></div>
<div class="chat-left" v-html="chat.message"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
&#13;
您可以使用Vue中的:class
属性添加条件类。