Skip to content

Commit 543ce50

Browse files
committedOct 13, 2021
reactive函数实现对象的响应式
1 parent 2e14787 commit 543ce50

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
 
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<template>
2+
<!--vue3的组件模版结构可以没有根标签-->
3+
<h1>我是app组件</h1>
4+
<h1>我叫{{ person.name }}, {{ person.age }}岁</h1>
5+
<h3>职位:{{ person.type }}</h3>
6+
<h3>薪水:{{ person.salary }}</h3>
7+
<h3>爱好:{{ person.hobbies }}</h3>
8+
<h4>测试的数据c:{{ person.a.b.c }}</h4>
9+
<button @click="changeInfo">修改人的信息</button>
10+
</template>
11+
12+
<script>
13+
import { reactive } from 'vue';
14+
export default {
15+
name: 'App',
16+
setup(){
17+
//表演的舞台(setup)
18+
//准备数据 data
19+
//ref实现响应式(基本类型)也是采用Object.definedProperty()来实现的 getter和setter
20+
// let name = ref('py'); //ref引用对象(RefImpl)实例
21+
// let age = ref(21);
22+
//ref实现响应式(对象类型)也是采用Proxy来实现(proxy) 这里如果就算是用ref也是借助了reactive
23+
let person = reactive({
24+
name: 'py',
25+
age: 21,
26+
type: 'frontend developer',
27+
salary: '30',
28+
hobbies: ['抽烟', '喝酒', '烫头'],
29+
a:{
30+
b:{
31+
c: 666
32+
}
33+
}
34+
});
35+
36+
37+
function changeInfo(){
38+
person.name = '李四';
39+
person.age = 42;
40+
// job.value.type = 'xxx'
41+
person.type = 'UI developer';
42+
//测试reactive能否监测深层次变化
43+
person.a.b.c = 100;
44+
person.hobbies[0] = 'play tennis';
45+
// console.log(name, age); //不是响应式的
46+
}
47+
48+
//返回一个对象
49+
return {
50+
person,
51+
changeInfo
52+
}
53+
}
54+
}
55+
</script>
56+
57+
<style>
58+
#app {
59+
font-family: Avenir, Helvetica, Arial, sans-serif;
60+
-webkit-font-smoothing: antialiased;
61+
-moz-osx-font-smoothing: grayscale;
62+
text-align: center;
63+
color: #2c3e50;
64+
margin-top: 60px;
65+
}
66+
</style>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//引入不再是Vue构造函数了,引入的是一个名为createApp的工厂函数
2+
//注意在这里无法像vue2那样去书写了,(这里并不兼容)
3+
import { createApp } from 'vue'
4+
import App from './App.vue'
5+
6+
//创建应用实例对象---app类似于vue2中vm,但app比vm更轻
7+
const app = createApp(App);
8+
// console.log(app);
9+
//挂载
10+
app.mount('#app');
11+
12+
// setTimeout(() => {
13+
// app.unmount("#app");
14+
// },2000)
15+
16+
// //vue2写法
17+
// const vm = new Vue({
18+
// render: h=> h(App)
19+
// });
20+
// vm.$mount('#app')

0 commit comments

Comments
 (0)
Please sign in to comment.