创建项目
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
# npm 6.x
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
# yarn
yarn create vite my-vue-app --template vue
# pnpm
pnpm create vite my-vue-app --template vue
安装后没有依赖,需要去安装依赖
yarn add i
nmp i
setup以及ref的使用
1.接收的数据可以是:基本类型、也可以是对象类型。
2.基本类型的数据:响应式依靠的是引用实现类上的getter与setter完成的
3.如果是复杂数据类型 他借助的是vue3中的响应式原理proxy来实现的 reactive()
<template>
<div>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{gender}}</h2>
<h2>{{job.sex}}</h2>
<button @click="a">+</button>
</div>
</template>
<script setup>
import {
ref
} from 'vue'
let name = "青阳子"
let age = ref(28)
let job = ref({
type: "前端工程师",
sex: "30",
});
let gender = "男"
const a = () => {
// age.value++;
console.log(age);
// console.log(job.sex.value);错误写法
console.log(job.value.sex++);
}
</script>
ref操作DOM
<template>
<div>
<h2 ref="qyz">{{age}}</h2>
<button @click="a">+</button>
</div>
</template>
<script setup>
import {
ref
} from 'vue'
const age = ref(30)
const qyz = ref(null)
const a = () => {
console.log(age.value++);
console.log(qyz);
qyz.value.style.color="red"
}
</script>
reacive的使用
1.reactive他不能用于基本数据类型的响应式
2.reactive底层运用的是vue3的响应式原理proxy 同时他不存在value
3.reactive用于复杂数据类型的响应式
<template>
<div>
<h2>{{job.age}}</h2>
<button @click="a">+</button>
</div>
</template>
<script setup>
import {
ref,reactive
} from 'vue'
let job = reactive({
name:'前端工程师',
age:30
})
const a = () => {
console.log(job.age++);
}
</script>
reactive丢失响应的办法
<template>
<div>
<h2>{{arr.list}}</h2>
<button @click="a">+</button>
</div>
</template>
<script setup>
import {
ref,
reactive
} from 'vue'
//reactive用于复杂数据类型的响应式 ?无效
// let arr = reactive([])
// const a = () => {
// console.log(arr);
// let res = ['2','3','4','5']
// arr = res
// }
// 方法一: let arr = reactive({
// list:[]
// })
// const a = () => {
// console.log(arr);
// let res = ['2','3','4','5']
// arr.list = res
// }
// 方法二:
let arr = ref([])
const a = () => {
console.log(arr);
let res = ['2','3','4','5']
arr.list = res
}
</script>
reactive响应是深层次的
<template>
<div>
<h2>{{lee.job.a.b.c}}</h2>
<h2>{{lee.hobby}}</h2>
<button @click="add">+</button>
<button @click="change">改变</button>
</div>
</template>
<script setup>
import {
ref,
reactive
} from 'vue'
let lee = reactive({
name: "青阳子",
age: 28,
hobby: ["写博客", "研究前端", "看电影"],
job: {
type: "前端工程师",
salary: "30K",
a: {
b: {
c: 111,
},
},
},
});
//1.说明reactive的响应式是深层次的
const add = () => {
console.log(lee);
lee.job.a.b.c++
}
const change = () => {
lee.hobby[0] = "旅游"
lee.hobby.push('唱歌')
}