一、refs 和 操作 DOM
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><div id="app" :style="{color: xColor}"><p ref="p1">{{msg}}</p><ul><!-- <li v-for="(item, index) in ary"v-if="index % 2 != 0"ref="listItem":key="index">{{item}}</li>--><li v-for="(item, index) in oddIndex"ref="listItem":key="index">{{item}}</li></ul></div><script src="vue.js"></script><script>// Vue 是数据驱动的,不提倡操作 DOM;但是必要的时候还是需要操作 DOM 的;Vue 为我们提供了专门的方式获取 DOM;// ref 属性和 vm.$refs// 如果这个列表不需要全部渲染,可以写一个计算属性,v-for 这个计算属性// 或者,v-if 条件渲染let vm = new Vue({el: '#app',data: {msg: 'hello',ary: [1, 2, 3, 4],xColor: ''},computed: {oddIndex() {return this.ary.filter((item, index) => index % 2 !== 0);}},mounted() {// console.log(this.$refs);console.log(this.$refs.p1);console.log(this.$refs.listItem);// 我们通过 this.$refs 获取 DOM 元素;this.$refs.p1.style.color = 'red'; // 可以实现,但是不推荐操作 DOM;// 首先要在获取的元素添加 ref="标识符" 的行内属性// 获取的时候 this.$refs.标识符 获取元素;// 如果相同的 ref 有一个,获取到的就是带这个 ref 的原生元素对象// 如果相同的 ref 有多个,获取到的是所有带有这个 ref 的元素组成的数组}})</script></body></html>
二、Vue-DOM 更新和 nextTick
<div id="app"><ul><li v-for="(item, index) in ary"ref="listItem":key="index">{{item}}</li></ul></div><script src="vue.js"></script><script>let vm = new Vue({el: '#app',data: {ary: [1, 3, 5]},mounted() {console.log(this.$refs.listItem.length);this.ary.push(7, 9);// console.log(this.$refs.listItem.length); // 为啥还是3?不是5呢?// 这是因为 Vue 更新 DOM 的机制是异步的;push 7,9后并没有直接就去更新 DOM,而是先等同步任务; 26行的 console 执行完,才去执行异步的更新 DOM;// 如果一定要获取更新数据以后的 DOM,要用 $nextTick;this.$nextTick(() => {// $nextTick 会把回调放到 DOM 更新以后执行console.log(this.$refs.listItem.length);})}})</script>
二、template
Vue 创建实例或者组件的时候,可以配置 template 属性,指定 vue 要渲染的模板;有两种使用方式;
- 在 html 中写一个 template 标签,把模板内容写在 template 标签中,绑定数据的语法和指令不变;然后在创建实例的时候添加 template 属性,值是 #template 标签的 id
- 指定一个字符串作为模板,字符串中要写绑定数据的 html 结构;在创建实例的时候,指定 template 属性,值就是模板字符串;
注意:
- template 属性会把根 DOM 节点替换掉
- template 属性只能有一个根节点(template 标签只能有一个子元素,如果是模板字符串,所有的内容要包裹在一个标签中)
<div id="app"></div><template id="tpl"> <!--模板渲染后,根 DOM 元素被替换掉了,template 标签本身不会被渲染到应用中--><div><button>{{msg}}</button><p>23456789</p><span>567890</span></div><!--<p>哈哈哈哈</p>--></template><script src="vue.js"></script><script>let vm = new Vue({// template: '#tpl',template: "<div>{{msg}} <p>2333333~</p></div>",el: '#app',data: {msg: 'hello world'}});</script>
