vue3学习d1
配置代码片段
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>