基础

template

The template HTML element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript.

template标签包裹的元素在页面是不显示的,右键检查可查看页面 DOM 结构。

template 元素是一种用于保存客户端内容的机制,该内容再加载页面时不会被呈现,但随后可以在运行时使用 JavaScript 实例化;

<!-- document-fragment -->
<template>
  <p>你看不见我</p>
</template>

为什么要写模板标签

反证,如果不写

不写template

Vue3 为什么可以不用写根元素

Vue 内部生成了虚拟根节点,参考 Fragment 新特性。

options

methods

0

<button @click="decrease">-</button>
<span style="margin-left:10px; margin-right:10px"> {{count}} </span>
<button @click="increase">+</button>
let count = ref(0);
function increase() {
  count.value++;
}
function decrease() {
  count.value--;
}

Vue2 内部遍历 methods 对象里面的方法,本质是使用bind()对 this 指向进行了显示绑定,所以 this 可以获取 data 里面的数据。Vue3 改用 setup 后就不用着 this 了,因为利用了作用域机制。

指令

v-model

收集表单数据open in new window

自定义 v-model

v-for

列表渲染 - Vue2

当 v-if 与 v-for 一起使用时,v-for 具有比 v-if 更高的优先级。

列表渲染 - Vue3

当它们处于同一节点,v-if 的优先级比 v-for 更高,这意味着 v-if 将没有权限访问 v-for 里的变量:

自定义指令

<p v-blink>文本闪烁{{second}}秒</p>

通过设置 directives 选项 ✅

directives: {
  blink: {
    mounted(el) {
      // el 获取DOM元素
      let isVisible = false;
      let timer = setInterval(()=>{
        isVisible = !isVisible
        el.style.visibility = isVisible ? "visible" : "hidden";
      },100)
      setTimeout(()=>{
        clearInterval(timer)
      },10000)
    }
  }
},

API

$refs

<h1 v-text="msg" ref="title"></h1>
<School ref="sch" />

vm.$refs 用来获取 DOM 元素或者组件实例对象。