第一章 【vue】基础(超详细)
Vue基础
Vue在HTML中的引入
<!-- 开发环境版本,包含了有帮助的命令行警告 --><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
使用Vue渲染数据
Vue可直接渲染定义在data里的数据,渲染动态数据使用“{{}}"包裹
示例代码
<div id="app">{{message}}<!-- 渲染对象 --><p>{{arr}}</p><!-- 渲染对象中具体的数值 --><p>{{arr.name}}</p><p>{{arr.age}}</p><!-- 渲染数组中具体的数值 --><p>{{obj[2]}}</p></div>
在js中挂载Vue实例
- Vue实列的作用范围:vue会管理el选项命中的元素及其后代元素
- 是否可以使用其他选择器 但是建议使用id选择器
- 是否可以设置其他的dom元素 可以使用其他的双标签 不能使用html和body
示例代码
var id = new Vue({//el 设置挂载点el: '#app',//date 数据对象 el实例需要的数据会定义在date中data: {message: 'hello vue!',arr: {id: 1,name: '张三',age: 18},obj: ['北京', '上海', '昆明', '安宁']}})
Vue模板语法
v-bind
v-bind的作用是为元素绑定属性
- 完整写法是v-bind:属性名
- 简写的话可以直接省略v-bind ":"+属性名
示例代码
<!--完整写法--><img v-bind:src="imgsrc" alt=""><!--简写--><img :src="imgsrc" alt="" :title="imgtitle" :height="100" :class="isactive?'active':''">
v-for
v-for指令 可以根据数据生成列表结构
- 数组经常和v-for结合使用
- 语法是(item,index)in 数据
- item代表每一项的数据
- index代表索引
- 数组长度的更新会同步到页面上 是响应式的
示例代码
<ul><li v-for="item in arr">{{item}}</li><li v-for="item in arraway">{{item.name}}</li><li v-for="(item,index) in arraway">{{index+1}}:{{item.age}}</li></ul>
v-html
v-html属性指令的作用是设置元素的innerHTML,相当于富文本解析
<div id="app"><h2>{{message}}</h2><h2 v-text="message"></h2><h2 v-html="message"></h2><!-- v-html属性指令的作用是设置元素的innerHTML --><h2 v-html="html"></h2></div><script>var app = new Vue({el: '#app',data: {message: '<button>开始</button>',html: '<a href="http://www.baidu.com">百度</a>'}})</script>
v-if
v-if根据表达式的真假直接操纵dom元素的显示与隐藏
- 当值为true时 元素存在于dom树中 当值为false时 从dom树中移除
- 频繁切换使用v-show反之使用v-if 前者的切换消耗小
示例代码
<div class="app"><div class="code" v-if="isshow"></div><button @click="changeisshow">切换显示</button></div><script>const app = new Vue({el: '.app',data: {isshow: true},methods: {changeisshow: function () {this.isshow = !this.isshow}}})</script>
v-else
v-else必须与v-if搭配使用 表示剩下的情况
示例代码
<div class="box"><div v-if="type=='A'">优秀</div><div v-else-if="type=='B'">良好</div><div v-else-if="type=='C'">一般</div><div v-else>差</div></div><script>const app = new Vue({el: '.box',data: {type: 'E'}})</script>