1.单文件夹响应式渲染点击自增
<script setup>
import { ref,onMounted } from 'vue'
const message = ref('Hello World!')
console.log(message.value) // "Hello World!"
message.value = 'Changed'
const counter = ref(0)
function increment(){
counter.value++
}
onMounted(()=>{
console.log(`${counter.value}`)
})
</script>
<template>
<h1>{{ message }}</h1>
<button @click = "increment">点我{{counter}}</button>
<p>Count is: {{ counter*2 }}</p>
</template>
2.点击按钮实现变色 Attribute 绑定
<script setup>
import { ref } from 'vue'
const message = ref('HELLO WORLD!')
const titleClass = ref('text-red')
function increment(){
titleClass.value = 'title-blue'
}
function increment2(){
titleClass.value = 'title-blue'
}
</script>
<template>
<h1 :class="titleClass">{{message}}</h1> <!-- 此处添加一个动态 class 绑定 -->
<button @click="increment">点我变红</button>
<button @click="increment2">点我变blue</button>
</template>
<style>
.title-red {
color: red;
}
.title-blue{
color:blue;
}
</style>
3.表单绑定 v-moudle语法糖
<script setup>
import { ref } from 'vue'
const text = ref('')
function onInput(e) {
text.value = e.target.value
}
</script>
<template>
<input :v-moudle="text" @input="onInput" placeholder="Type here">
<p>{{ text }}</p>
</template>
4.if else 的使用
<script setup>
import { ref } from 'vue'
const awesome = ref("")
function toggle() {
awesome.value = ''
}
function checkInput(){
return awesome.value == '121'
}
</script>
<template>
<button @click="toggle">清空输入</button>
<input type="text" v-model="awesome">
<h1 v-if= "checkInput()">hello world!</h1>
<h1 v-else>Oh no 😢</h1>
</template>
5.v-for
<script setup>
import { ref } from 'vue'
// 给每个 todo 对象一个唯一的 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" required placeholder="new todo">
<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>
浙公网安备 33010602011771号