Skip to content

Commit

Permalink
vue3中的shallowReactive和shallowRef
Browse files Browse the repository at this point in the history
  • Loading branch information
Panyue-genkiyo committed Oct 13, 2021
1 parent 91eab35 commit e770d7e
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 14_src_shallowRef和shallowReactive/App.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<template>
<!--vue3的组件模版结构可以没有根标签-->
<button @click="isShowDemo = !isShowDemo">{{ isShowDemo ? '隐藏' : '显示'}}</button>
<Demo v-if="isShowDemo"/>
</template>

<script>
import Demo from "./components/Demo";
import { ref } from "vue";
export default {
name: 'App',
components: {Demo},
setup(){
let isShowDemo = ref(true);
return {
isShowDemo
}
}
}
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
65 changes: 65 additions & 0 deletions 14_src_shallowRef和shallowReactive/components/Demo.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<template>
<h2>当前的y是:{{ x.y }}</h2>
<button @click="x = {y : 888}">点我替换x</button>
<button @click="x.y++">点我y+1</button>
<hr/>
<h4>{{ person }}</h4>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>薪资:{{ job.j1.salary }}K</h2>
<button @click="name = name + '~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="job.j1.salary++">增长薪资</button>
</template>

<script>
import {ref,reactive, toRefs, shallowReactive, shallowRef} from 'vue';
export default {
name: 'Demo',
setup(){
//shallowReactive只考虑对象类型的第一层数据响应式
// let person = shallowReactive({
// name: '张三',
// age: 18,
// job:{
// j1:{
// salary: 20
// }
// }
// });
let person = reactive({
name: '张三',
age: 18,
job:{
j1:{
salary: 20
}
}
});
// let x = ref(0);
//传递基本类型来说,ref与shallowRef基本是没什么区别的
// let x = shallowRef(0);
//但注意对象类型shallowRef不去处理,而ref底层回去借助reactive生成proxy对象(getter/setter)
//但注意不管是shallowR还是非shallow, 第一层都是响应式的(不如下面的x依然是响应式数据)
let x = shallowRef({ y: 0 });
console.log(x);
// let x = ref({ y: 0 })
return {
person,
...toRefs(person),
x,
};
}
}
</script>

<style>
</style>

20 changes: 20 additions & 0 deletions 14_src_shallowRef和shallowReactive/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//引入不再是Vue构造函数了,引入的是一个名为createApp的工厂函数
//注意在这里无法像vue2那样去书写了,(这里并不兼容)
import { createApp } from 'vue'
import App from './App.vue'

//创建应用实例对象---app类似于vue2中vm,但app比vm更轻
const app = createApp(App);
// console.log(app);
//挂载
app.mount('#app');

// setTimeout(() => {
// app.unmount("#app");
// },2000)

// //vue2写法
// const vm = new Vue({
// render: h=> h(App)
// });
// vm.$mount('#app')

0 comments on commit e770d7e

Please sign in to comment.