vue笔记
2024年5月19日大约 2 分钟
vue笔记
程序入口位于 main.js
通过 import 引入 vue 项目文件,例如:import Test from './test.vue'
随后将导入的项目传入 createApp 函数(也不知道这是什么,只知道要这么做)const test = createApp(Test)
使用成员函数 mount 绑定渲染的 css 选择器test.mount("#t1")
这样,模板里的内容就会被渲染到 id="t1" 的容器上
html 通过 script 标签引入 vue
<script type="module" src="/src/main.ts"></script>
vue 响应式
通过 ref/reactive 两个函数创建响应式的变量 / 对象
import { ref,reactive } from 'vue' //引入ref和reactive
两者的区别为 ref
接受一个单一值作为参数,而 reactive
接受一个对象作为参数去初始化,例如:
const t1 = ref(0);
const t2 = reactive({
name: "lihua"
id: "110xxxxxxxxxxxxxxx"
phone: 1145142986
})
在使用时这两有点区别在于:ref 初始化的,在 script 标签内需要使用 name.value 进行操作,而在 template 中则是直接使用自己的名称,例:
<script setup lang="ts">
import { ref,reactive } from 'vue'
const t1 = ref(0)
function f1(){
t1.value++ //在script标签内需要使用name.value进行操作
}
</script>
<template>
<button @click="f1">add</button>
<br>
<p>{{t1}}</p> //在template中则是直接使用自己的名称
</template>
而 reactive 则是像正常的 js 对象一样使用。成员操作符进行操作
绑定 HTML class
使用:class (v-bind:class 的缩写) 实现
<div :class={"class1": bool1}></dev>
当 bool1=true 时将会把 class1 渲染出来,如下:
<div class="class1"></div>
条件渲染
使用 v-if,v-else-if,v-else 实现
// num=3
<h1 v-if="num==1">1</h1>
<h1 v-else-if="num==2">2</h1>
<h1 v-else="num==3">3</h1>
实际渲染在 html 中的结果为
<h1>3</h1>
列表渲染
使用 v-for 可以循环整个对象
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
<li v-for="item in items">
{{ item.message }}
</li>