在实现Hello World程序前,我们必须先引入VueJs。
<script src="https://unpkg.com/vue@3/dist/vue.global.js"> </script>
写一个单标签作为容器进行演示:
<div id="app"></div>
创建应用
<script>
//创建Vue应用
Vue.createApp({
//入口函数
setup() {
//数据准备
const msg = 'Hello World'
//返回数据对象
return{
msg
}
}
}).mount('#app') //内容渲染到id == app 的盒子里
</script>
渲染数据
<div id="app">
<h1>{{ msg }}</h1>
<!-- 渲染数据 -->
</div>
setup
函数是Vue3API的入口函数
setup
函数是Vue3的特有选项,作为编写代码的起点。this
不是Vue的实例,setup中是不会用到this的{{ 表达式 }}
被称为插值表达式
前端中常见的表达式有:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>{{ msg }}</h1>
<p>我的名字为{{Stu.name}}我今年{{Stu.age}}岁了</p>
<p>是{{ Stu.age >= 18 ?'成年人':'未成年人'}}哦</p>
<p>明年就{{ Stu.age+1 }}岁了</p>
<p>fn的返回值{{ fn() }}</p>
<!-- 渲染数据 -->
</div>
</body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"> </script>
<script>
//创建Vue应用
Vue.createApp({
//入口函数
setup() {
//数据准备
const msg = 'Hello World' //字符串
const Stu = {
name:'Yui',
age:17
} // 对象
function fn(){
return 520
}//函数
//返回数据对象
return{
msg,
Stu,
fn
}
}
}).mount('#app') //内容渲染到id == app 的盒子里
</script>
</html>
数据响应式就是数据变,界面自动变,无需手动操作 DOM。
有两种方法:
安装成功后,打开开发者工具后,你会看到一个Vue调试板
在先前的样例中,setup中默认返回的数据是不具备响应式特性的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>我的名字为{{Stu.name}}我今年{{Stu.age}}岁了</p>
<!-- 渲染数据 -->
</div>
</body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"> </script>
<script>
const {reactive} = Vue
//创建Vue应用
Vue.createApp({
//入口函数
setup() {
const Stu = reactive({
name: 'Yui',
age: 17
} )// 对象
return {
Stu
}
}
}).mount('#app') //内容渲染到id == app 的盒子里
</script>
</html>
注意: reactive函数的参数只能是对象
ref的作用和reactive类似,但是参数不限制类型。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>我的名字为{{Stu.name}}我今年{{Stu.age}}岁了</p>
<h1>{{ msg }}</h1>
<!-- 渲染数据 -->
</div>
</body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"> </script>
<script>
const {reactive,ref} = Vue
//创建Vue应用
Vue.createApp({
//入口函数
setup() {
const Stu = reactive({
name: 'Yui',
age: 17
} )// 对象
const msg = ref("Hello World")
return {
Stu,
msg
}
}
}).mount('#app') //内容渲染到id == app 的盒子里
</script>
</html>
注意:操作ref创建的数据,JS中需要.value
,template
中不用。
如果数据是对象,并且字段也确定,推荐使用reactive,其他都用ref
声明式渲染和数据响应式都是Vue3的重要特点,需要熟练掌握。
往期内容: Vue3入门-必会前置知识-CSDN博客