Vue3 基础

Vue3 基础

响应式

监听数据改动并自动更新。

使用ref()reactive()包装值,生成Proxy代理,劫持对象的调用和操作。
get时,将自身添加为被依赖值,进行依赖收集。(effect中会设置当前执行的函数)
set时,触发更新,重新调用依赖自身的函数。

绑定属性

  • 全写:v-bind:name="xxx"
  • 简写::name="xxx"

绑定事件

  • 全写:v-on:event="xxx"
  • 简写:@event="xxx"

事件修饰符:@event.modifier
详情

  • .stop 停止传递
  • .prevent 阻止默认事件(preventDefault()

绑定按键

@keydown.key-name
@keyup.key-name

可以使用KeyboardEvent.key中的按键名称,需要把名字转换为kebab-case(小写字母、横线分隔)。
例如.enter.page-down

可以使用修饰键:.ctrl .alt .shift .meta
例如@keyup.alt.enter

按住Ctrl时点击触发事件:@click.ctrl

精确按键:.exact

双向绑定

组合绑定属性和事件

<input :value="text" @input="onInput">
function onInput(e){
    text.value = e.target.value;
}

简写

<input v-model="text">

v-model可以适配多种输入控件。

  • .lazy:默认在input事件时更新数据,用v-model.lazy改为change事件时触发。
  • .trim:更新数据为trim后的字符串

条件渲染

<div v-if="xxx"> ... </div>
<div v-else-if="xxx"> ... </div>
<div v-else> ... </div>

列表渲染

带有v-for属性的元素本身会被重复渲染。

<ol>
    <li v-for="foo in bar">
        {{ foo.text }}
    </li>
</ol>

列表更新、元素顺序改变时,默认“就地更新”,不会移动渲染元素的顺序。渲染元素依赖有状态的组件时,相性不好。

添加key属性允许vue跟踪已有的渲染元素,能够重用、重排已有的渲染元素。

<ol>
    <li v-for="foo in bar" :key="foo.id">
        {{ foo.text }}
    </li>
</ol>

计算属性

依赖变更时自动调用函数更新数值。

const foo = computed(() => ...);

let bar = foo.value;

侦听器

数值变更时调用函数

const count = ref(0);

watch(count, (v) => ...);

自定义属性

const props = defineProps({
    text: String
});

props.text
<FooComponent text="bar"/>

插槽

用来往组件内插入HTML片段。
父组件没有传入内容时,才会使用子组件slot标签中的内容。

默认插槽:

<!-- Parent -->
<ChildComponent>AAA</ChildComponent>

<!-- ChildComponent -->
<slot>Fallback Content</slot>

多个插槽:

<!-- Parent -->
<ChildComponent>
    <template v-slot:header>Header</template>
    <template v-slot:body>Body</template>
    <template v-slot:footer>Footer</template>
</ChildComponent>

<!-- ChildComponent -->
<slot name="header"></slot>
<slot name="body"></slot>
<slot name="footer"></slot>

生命周期

onLifecycle(() => ...);

生命周期图示

生命周期图示生命周期图示

评论已关闭