一、 模板语法
Vue 使用一种基于 HTML 的模板语法,使我们能够声明式地将其组件实例的数据绑定到呈现的 DOM 上。所有的 Vue 模板都是语法层面合法的 HTML,可以被符合规范的浏览器和 HTML 解析器解析。
英文官网: Vue.js - The Progressive JavaScript Framework | Vue.js
中文官网: https://cn.vuejs.org/
HTML中包含了一些 JS 语法代码,语法分为两种
1. 插值(双大括号{{ }}表达式)
2. 指令(以 v-开头)
二、响应式基础
1、ref()
ref()
在组合式 API 中,推荐使用 ref() 函数来声明响应式状态
ref()
接收参数,并将其包裹在一个带有.value
属性的 ref 对象中返回
<script setup>
import { ref } from 'vue'
// “ref”是用来存储值的响应式数据源。
const count = ref(100)
const msg=ref('Hello Using Vue.js ref()')
function add() {
count.value++ //ref包裹在一个带有 .value 属性
}
function updates(){
msg.value=msg.value.split('').reverse().join('').concat('!'); //修改一个 ref 的值。
}
</script>
<style>
</style>
<template>
<div>注册<p/>
<h1>{{msg}}</h1>
<button @click="add">{{count}}</button><br/><br/>
<button @click="updates">{{msg}}</button>
</div>
</template>
2、reactive()
reactive 是在Vue3 中一个用于创建响应式数据的函数。它可以将普通 JavaScript 对象转换为响应式对象,使其能够在数据变化时自动更新视图。
reactive注意点
<script setup>
//reactive使用
import { reactive } from 'vue';
const numbers=reactive(1000) //定义一个基本数据类型
//定义对象
const data=reactive({
name:'张三',
age:18,
gender:'男'
})
//修改数据,视图自动更新
data.name="interface"
</script>
<style>
</style>
<template>
<div>注册<p/>
<h1>{{msg}}</h1>
<button @click="add">{{count}}</button><br/><br/>
<button @click="updates">{{msg}}</button><br/><br/>
<span>{{data.name}},{{data.age}},{{data.gender}} / {{numbers}}</span><br/>
</div>
</template>
优点:
- 响应式视图:reactive 使得创建响应式视图变得容易,无需手动管理依赖关系。
- 性能优化:Vue.js 仅在数据更改时更新视图,从而提高性能。
- 易用性:reactive 函数简单易用,可简化应用程序开发。
三、属性Attribute绑定
使用双大括号{{}}的写法,可以将数据解释为纯文本,但是是不能动态绑定HTML的attributes的,要想绑定attribute就需要用v-bind指令
v-bind:可以简写为冒号:,如v-bind:id="top"写成 :id="top"
<div :id="dynamicId"></div>
因为
class
和style
都是 attribute,我们可以和其他 attribute 一样使用v-bind
将它们和动态的字符串绑定Vue 专门为
class
和style
的v-bind
用法提供了特殊的功能增强。除了字符串外,表达式的值也可以是对象或数组。
<script setup>
import {ref} from 'vue'
//颜色
const color=ref('blue')
const dynamicId=ref('titles')
function toggleColor(){
color.value=color.value=='blue'?'red':'blue'
}
</script>
<template>
<div :id="dynamicId">
<span>动态绑定</span><br/>
<!-- 样式绑定也支持对象和数组 -->
<span :style='{color}' @click="toggleColor">
改变字体颜色!!
</span>
</div>
</template>
<style>
#titles{
font-size: 32px;
background: gray;
}
span{
display: block;
}
</style>