Skip to content

Commit

Permalink
vue3中的watchEffect函数
Browse files Browse the repository at this point in the history
  • Loading branch information
Panyue-genkiyo committed Oct 13, 2021
1 parent 0692b3c commit 44eeae4
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 0 deletions.
25 changes: 25 additions & 0 deletions 10_src_watchEffect函数/App.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<template>
<!--vue3的组件模版结构可以没有根标签-->
<Demo/>
</template>

<script>
import Demo from "./components/Demo";
export default {
name: 'App',
components: {Demo},
setup(){
}
}
</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>
64 changes: 64 additions & 0 deletions 10_src_watchEffect函数/components/Demo.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<template>
<h1>当前求和为:{{ sum }}</h1>
<button @click="sum++">点我加一</button>
<hr/>
<h2>当前的信息为:{{ msg }}</h2>
<button @click="msg += '!'">修改信息</button>
<hr/>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<h2>薪资:{{ person.job.j1.salary }}K</h2>
<button @click="person.name = person.name + '~'">修改姓名</button>
<button @click="person.age++">增长年龄</button>
<button @click="person.job.j1.salary++">增长薪资</button>
</template>

<script>
import {reactive, ref, watch, watchEffect} from 'vue';
export default {
name: 'Demo',
setup(){
let sum = ref(0);
let msg = ref('你好');
let person = reactive({
name: '张三',
age: 18,
job:{
j1:{
salary: 20
}
}
});
//监测的不是一个值,而是一个保存值的结构(不能写成sum.value) 不能监视一个具体的值注意
watch(sum, (nv, ov) => {
console.log(nv, ov);
},{
immediate: true
});
//watchEffect
//不确定监视对象
//默认开启了immediate:true
watchEffect(() => {
console.log(`watch effect指定的回调执行了!!`)
//依赖收集,你用到了谁它就监视谁!!
//这里用到sum了
const x1 = sum.value;
const x2 = person.job.j1.salary;
})
//返回一个对象
return {
sum,
msg,
person
}
}
}
</script>

<style>
</style>
20 changes: 20 additions & 0 deletions 10_src_watchEffect函数/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 44eeae4

Please sign in to comment.