Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d246901

Browse files
committedOct 12, 2021
vue中ref实现数据响应式(defineProperty,Proxy)
1 parent c81da2d commit d246901

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
 

‎03_src_ref函数的使用/App.vue

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<template>
2+
<!--vue3的组件模版结构可以没有根标签-->
3+
<h1>我是app组件</h1>
4+
<h1>我叫{{ name }}, {{ age }}岁</h1>
5+
<h3>职位:{{ job.type }}</h3>
6+
<h3>薪水:{{ job.salary }}</h3>
7+
<button @click="changeInfo">修改人的信息</button>
8+
</template>
9+
10+
<script>
11+
import { ref } from 'vue';
12+
export default {
13+
name: 'App',
14+
setup(){
15+
//表演的舞台(setup)
16+
//准备数据 data
17+
//ref实现响应式(基本类型)也是采用Object.definedProperty()来实现的 getter和setter
18+
let name = ref('py'); //ref引用对象
19+
let age = ref(21);
20+
//ref实现响应式(对象类型)也是采用Proxy来实现
21+
let job = ref({
22+
type: 'frontend developer',
23+
salary: '30'
24+
});
25+
26+
function changeInfo(){
27+
name.value = '李四';
28+
age.value = 42;
29+
job.value.type = 'UI developer';
30+
console.log(name, age); //不是响应式的
31+
}
32+
33+
//返回一个对象
34+
return {
35+
name,
36+
age,
37+
job,
38+
changeInfo
39+
}
40+
}
41+
}
42+
</script>
43+
44+
<style>
45+
#app {
46+
font-family: Avenir, Helvetica, Arial, sans-serif;
47+
-webkit-font-smoothing: antialiased;
48+
-moz-osx-font-smoothing: grayscale;
49+
text-align: center;
50+
color: #2c3e50;
51+
margin-top: 60px;
52+
}
53+
</style>

‎03_src_ref函数的使用/main.js

+20
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.