Vue数据渲染
如何渲染
- 渲染的语法:{{…要渲染的内容}} —— 需要用两个花括号括起来
- 要渲染的数据必须是 this 作用域可访问到的.
- 要渲染的数据放在 data() 中
简单渲染
1.首先在 data() 中定义需要渲染的字段并赋值 。
data() {
return {
msg: 'hello vue!'
}
}
2.其次,用已经定义的字段,将其渲染在页面上。
<template>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg: 'hello vue'
}
}
}
</script>
效果:
函数渲染
比如有一个时间类型的字段:
data() {
return {
time: new Date()
}
}
使用表达式渲染完成封装:
{{ time.getFullYear() + "年" + time.getMonth() + "月" + time.getDate() + "日" + time.getHours() + "时" + time.getMinutes() + "分" + time.getSeconds()+ "秒" }}
效果如下:
渲染单个变量,数组
<template>
<div>
{{name}}--{{age}}<br />
<ul>
<li v-for="(item ,index) in list " :key="index">
{{item}}
</li>
</ul>
</div>
</template>
<script>
export default{
data(){
return{
name:'小红',
age:'20',
list:['足球','篮球']
}
}
}
</script>
效果如下:
(1)渲染单个变量使用双花括号
(2)v-for:使用v-for把一个数组对应为一组元素用v-for指令根据一组数组的选项列表进行渲染