Skip to content

Commit

Permalink
vue3中的readOnly和shallowReadOnly
Browse files Browse the repository at this point in the history
  • Loading branch information
Panyue-genkiyo committed Oct 13, 2021
1 parent dd76b1f commit 3e9b239
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 15_src_readOnly和shallowReadOnly/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>
48 changes: 48 additions & 0 deletions 15_src_readOnly和shallowReadOnly/components/Demo.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<template>
<h2>当前求和为:{{ sum }}</h2>
<button @click="sum++">sum+1</button>
<hr/>
<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, readonly, shallowReadonly} from 'vue';
export default {
name: 'Demo',
setup(){
let sum = ref(0);
let person = reactive({
name: '张三',
age: 18,
job:{
j1:{
salary: 20
}
}
});
// person = readonly(person); //此时person里面的属性值都不允许修改
//person = shallowReadonly(person); //第一层不能改(name,age), 但j1和salary仍然可以改动
// sum = readonly(sum); //同理
// sum = shallowReadonly(sum)
return {
sum,
...toRefs(person),
};
}
}
</script>

<style>
</style>

20 changes: 20 additions & 0 deletions 15_src_readOnly和shallowReadOnly/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 3e9b239

Please sign in to comment.