vue3基础语法(一)
1.声明式呈现
<script setup>
import { reactive, ref } from 'vue'
const counter = reactive({ count: 0,number:10 })
const message = ref('Hello World!')
</script>
<template>
<h1>{{ message }}</h1>
<p>Count is: {{ counter.count }}</p>
<p>
number is :{{counter.number}}
</p>
</template>
ref
: 用于定义一个响应式的数据引用。ref
接受一个内部值并返回一个响应式且可变的对象,该对象具有一个 .value
属性指向内部值。当你在模板中直接使用 ref
创建的变量时,Vue 会自动解包 .value
,也就是说你在输入count时,vue会默认为vue.value。
reactive
: 接受一个普通对象并返回该对象的响应式代理。可以用来创建一个响应式的对象。当你修改对象的属性时,视图会自动更新。它对嵌套对象也起作用。
2.属性绑定
import { ref } from 'vue'
const titleClass = ref('title')
</script>
<template>
<h1 :class="titleClass">Make me red</h1>
</template>
<style>
.title {
color: red;
}
</style>
我们一般使用v-bind来绑定属性,但是因为使用频率很高,所以也可以直接缩写为':'
3.事件监听器
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">count is: {{ count }}</button>
</template>
一般使用v-on:click来实现,但是频率很高,所以也可以缩写为 @click
4.表单绑定
import { ref } from 'vue'
const text = ref('')
</script>
<template>
<input v-model="text" placeholder="Type here">
<p>{{ text }}</p>
</template>
原理是通过v-bind,v-on来实现双向绑定,但是我们为了简化,可以直接使用v-model来实现
也可以用上面的这个代码
5.条件渲染
import { ref } from 'vue'
const awesome = ref(true)
function toggle() {
awesome.value = !awesome.value
}
</script>
<template>
<button @click="toggle">toggle</button>
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
</template>
仅当 传入的值为 true 时,才会呈现此值。如果更改为虚假值,则会将其从 DOM 中删除。 除了v-if还有v-else来表示这些条件,这样我们在点击按钮的时候就会进行切换了
6.列表呈现 用v-for函数来实现
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
</li>
</ul>
这是一段综合代码
import { ref } from 'vue'
// give each todo a unique id
let id = 0
const newTodo = ref('')
const todos = ref([
{ id: id++, text: 'Learn HTML' },
{ id: id++, text: 'Learn JavaScript' },
{ id: id++, text: 'Learn Vue' }
])
function addTodo() {
todos.value.push({ id: id++, text: newTodo.value })
newTodo.value = ''
}
function removeTodo(todo) {
todos.value = todos.value.filter((t) => t !== todo)
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<button>Add Todo</button>
</form>
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
</template>
在这里有两种方法更新数组 1.push 2.filter 在这里讲一下filter的用法
const filteredNumbers = numbers.filter(number => number > 10);
console.log(filteredNumbers); // 输出: [12, 23, 18]
在这个例子中,filter
方法接受了一个箭头函数作为回调。这个箭头函数接受number
作为参数,并返回一个布尔值,表示number
是否大于10。filter
方法遍历numbers
数组中的每个元素,并使用这个箭头函数来检查每个元素。最后,它返回一个新数组filteredNumbers
,包含所有通过测试的元素。
7.conputed属性
import { ref, computed } from 'vue';
const apples = ref(3); // 苹果的数量
const oranges = ref(5); // 橘子的数量
// 使用 computed 创建一个计算属性
const totalFruits = computed(() => apples.value + oranges.value);
</script>
<template>
<div>苹果的数量: {{ apples }}</div>
<div>橘子的数量: {{ oranges }}</div>
<div>水果总数: {{ totalFruits }}</div>
</template>
可以理解为,这样我修改一个水果数量的值,总数值会跟着改变
转载自:https://juejin.cn/post/7304562756429676582