vue3-setup、响应式

vue-cli脚手架

cmd: npm create vue@latest

vscode

.vscode:里面是vscode本身的配置资源
src:自己写的源代码文件
.ico:页签图标
有文件标红:终端 npm i 会下载所有需要的依赖

image
该句让.ts可以认识所有可能会用到的文件类型

image
均是ts的配置文件

vite.config.ts:用于配置文件,配置代理一些东西

main.ts中

import {createApp} from 'vue'  <!--创建应用-->
import App from './App.vue' <!--创建组件-->
createApp(App).mount('#app") <!--createApp(App)是建立根基根基为App  .mount('#app')是挂载容器 在index.html的 <div id='app'/>中-->``

image

配置代码片段

vscode的菜单->文件->首选项->代码判断->输入vue在vue.json中写好“vue template”

setup

<script setup lang="ts">  //vue3中有了setup则会自动处理组件导出,不需要export default 
import Person from "./components/Person.vue" //直接导入组件即可
</script>

setup(){
//数据
let ...
//方法
function (){}

return {数据,function}}
  • 和data methods区别
    setup、data、methods可以同时存在,data中可以读取setup中的数据,反之不行(setup声明周期比data早)

  • setup语法糖

<script setup lang="ts" name="person234">  //name是组件名字,需要配置插件npm i vite-plugin-vue-setup-extend -D 再vite.config.ts中配置
let name = "zhangsan";
let age = 18;
let tel = "1234567890";
//方法
function changeName() {
  name = "lisi";
}
function changeAge() {
  age = 20;
}
function showTel() {
  alert(`联系方式:${tel}`);
}
</script>

响应式数据

  • ref 基本类型的数据、对象类型
import { ref } from "vue";
let name = ref("zhangsan");
let age = ref(18);
```vue
function changeName() {
  name.value = "lisi";
}
function changeAge() {
  age.value = 20;
}

要想ref包裹对象类型数据,注意car.value.price 、games.value[0].price
需要.value

  • reactive 只能定义对象类型的数据
    proxy:代理(js内置的函数)
<script setup lang="ts" name="person">
import { reactive } from "vue";
let car = reactive({ brand: "宝马", price: 80 });
console.log(car);
function changePrice() {
  car.price = 100;
}
let games = reactive([{ name: "王者荣耀", price: 1 },
  { name: "和平精英", price: 2 },
  { name: "英雄联盟", price: 3 }])
function changePrice2() {
  games[0].price = 10;
  games[1].price = 20;
  games[2].price = 30;
}
</script>
posted on 2025-08-17 17:59  Siannnn  阅读(12)  评论(0)    收藏  举报