目录
- <template>
- <h1>一个人的信息</h1>
- 姓:<input type="text" v-model="person.firstName">
- 名:<input type="text" v-model="person.lastName">
- <br>
- <span>全名:{{person.fullName}}</span>
- </template>
-
- <script>
- import {reactive,computed} from 'vue'
- export default {
- name: 'HelloWorld',
-
- setup(){
- //数据
- let person = reactive({
- firstName:'张',
- lastName:'三'
- })
-
- //计算属性(简写 没有考虑计算属性被修改的情况)
- person.fullName = computed(()=>{
- return person.firstName +'-'+person.lastName
- })
- //计算属性(完整写法 考虑读和写)
- person.fullName = computed({
- get(){
- return person.firstName +'-'+person.lastName
- },
- set(){
- const nameArr = value.split('-')
- person.firstName = nameArr[0]
- person.lastName = nameArr[1]
- }
- })
-
- //返回一个对象(常用)
- return {
- person,
- }
- }
- }
- </script>
-
-
-
-
下面有六种情况:
- <template>
- <h1>当前求和为:{{sum}}</h1>
- <button @click="sum++">点我+1</button>
- <hr>
- <h1>当前信息:{{msg}}</h1>
- <button @click="msg+='!'">点我修改</button>
- </template>
-
- <script>
- import {ref,watch} from 'vue'
- export default {
- name: 'HelloWorld',
-
- setup(){
- //数据
- let sum = ref(0)
- let msg = ref('你好啊')
-
- //情况1:监视ref所定义的一个响应式数据
- watch(sum,(newValue,oldValue)=>{
- console.log('sum变了',newValue,oldValue)
- },{immediate:true})
-
- //情况2:监视ref所定义的多个响应式数据
- watch([sum,msg],(newValue,oldValue)=>{
- console.log('sum或msg变了',newValue,oldValue)
- },{immediate:true})
-
- //返回一个对象(常用)
- return {
- sum,
- msg
- }
- }
- }
- </script>
-
- <!-- Add "scoped" attribute to limit CSS to this component only -->
-
-

- <template>
- <h1>姓名:{{person.name}}</h1>
- <h1>年龄:{{person.age}}</h1>
- <h1>薪资:{{person.job.j1.salary}}</h1>
- <button @click="person.name+='!'">点我改姓名</button>
- <button @click="person.age++">点我增长年龄</button>
- <button @click="person.job.j1.salary++">增长薪资</button>
- </template>
-
- <script>
- import {reactive,watch} from 'vue'
- export default {
- name: 'HelloWorld',
-
- setup(){
- //数据
- let person = reactive({
- name:'张三',
- age:18,
- job:{
- j1:{
- salary:20
- }
- }
- })
-
-
- //情况3:监视reactive所定义的一个响应式数据
- // 1、注意:此处无法正确获取oldValue
- // 2、注意:强制开启了深度监视(deep配置无效)
- watch(person,(newValue,oldValue)=>{
- console.log('peson变了',newValue,oldValue)
- },{deep:false}) //此处的deep配置无效
- //情况4:监视reactive所定义的一个响应式数据中的某一个属性
- watch(()=>person.name,(newValue,oldValue)=>{
- console.log('peson的name变了',newValue,oldValue)
- })
- //情况5:监视reactive所定义的一个响应式数据中的某些属性
- watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
- console.log('peson的name和age变了',newValue,oldValue)
- })
- //特殊情况
- watch(()=>person.job,(newValue,oldValue)=>{
- console.log('peson的job变了',newValue,oldValue)
- },{deep:true}) //此处由于监视的是reactive所定义的对象的某个属性,所以deep
- 配置有效
-
- //返回一个对象(常用)
- return {
- person
- }
- }
- }
- </script>
-
-
-

- //watchEffect所指定的回调中用到的数据只要发生了变化,则直接重新执行回调。
- watchEffect(()=>{
- const x1 = sum.value
- const x2 = person.job.j1.salary
- console.log('watchEffect执行了')
- })
函数内用到了sum和person下的salary,所以只要这两个数据变化了,就会执行监视。点击其他的就不会执行。
