一、安装vue3+vite环境
npm init vite@latest
-
切换到你想安装的盘符下面,再运行上面代码(如果出错以管理员运行cmd)
-
接着运行给你的三条命令
-
安装成功,在浏览器运行地址
二、入口文件main.js
1. Vue2的写法
new Vue({
render: h => h(App)
}).$mount('#app')
2.Vue3的写法
// 创建应用实例对象-app(类似于之前的vue2 vm 但app比vm更轻)
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
const app = createApp(App);
console.log(app);
app.mount('#app')
3.mount挂载 unmount卸载
// 等一秒之后卸载
setTimeout(()=>{
app.unmount();
},1000)
注意 不能在vue3中写这样的代码
import Vue from 'vue'
console.log(Vue);
在vue3中可以没有根标签
三、setup
1.理解
理解:Vue3.0中一个新的配置项,值为一个函数。
-
setup是所有Composition API(组合API) “ 表演的舞台 ” 。
-
组件中所用到的:数据、方法等等,均要配置在setup中。
-
setup函数的两种返回值:
- 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)
- 若返回一个渲染函数:则可以自定义渲染内容。(了解)
2.实例演示
1.返回一个对象
<template>
<div>
<h1>我是Test组件</h1>
<h1>{{ name }}-{{ age }}</h1>
<button @click="sayHello">点我</button>
</div>
</template>
<script>
export default {
name:'Test',
setup(){
// 数据
let name = "张三";
let age = 18;
function sayHello(){
alert(`姓名:${name},年龄${age},你好啊`);
}
return {
name,
age,
sayHello,
}
}
}
</script>
2.渲染函数
return () => h('h1', '尚硅谷');
// 渲染函数 直接把template里面的元素替换
3.注意点:
尽量不要与Vue2.x配置混用
- Vue2.x配置(data、methos、computed...)中可以访问到setup中的属性、方法。
- 但在setup中不能访问到Vue2.x配置(data、methos、computed...)。 如果有重名, setup优先。
- setup不能是一个async函数,因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)
实例演示-演示上述的注意点
<template>
<div>
<h1>我是Test组件</h1>
<h1>{{ name }}-{{ age }}-{{ sex }}</h1>
<button @click="sayWelcome">点我</button>
<!-- 成功读取 -->
<button @click="test1">在vue2 的methods中读取vue3中的配置</button>
<!-- vue3中并不能读取vue2中的数据 因为this的指向时一个代理对象 -->
<button @click="test2"> 在vue的setup中读取vue的配置</button>
<p>冲突时以vue3为准 a:{{ a }}</p>
</div>
</template>
<script>
import { h } from 'vue'
export default {
name: 'Test',
data() {
return {
sex: '男',
a:200,
}
},
methods: {
sayWelcome() {
alert('欢迎来看我的Blog')
},
test1() {
console.log('fds');
console.log(this.sex);
console.log(this.name);
this.sayHello()
},
},
setup() {
// 数据
let name = "张三";
let age = 18;
let a = 300;
function sayHello() {
alert(`姓名:${name},年龄${age},你好啊`);
}
function test2(){
console.log(age);
console.log(sayHello);
// Proxy {name: '张三', age: 18, sayHello: ƒ, test2: ƒ}
console.log(this);
console.log(this.sex);
}
return {
name,
age,
sayHello,
test2,
a
}
// return () => h('h1', 'Tina');
// 渲染函数 直接把template里面的元素替换
}
}
</script>
<style lang="scss" scoped></style>