vue3

1、ref 深拷贝 视图层更新不改变源数据

const num = 1
const refNum = ref(num)
const click = ()=>{
  refNum++  //refNum 已经改变了,但原数据num不变
}

2、toRef 源数据改变不更新视图

3、toRefs 传入一个响应式对象

const obj =reactive{name:"iwen",age:19}//取值为obj.name
return (...toRefs(obj))//取值为name age

  

 4、计算属性

import {computed} from "vue"
const sum = computed(()=>{
   return a + b 
})

5、监听函数

import {watch} from "vue"
watch(p,(oldVal,newVal)=>{
   console.log(oldVal,newVal) 
})

6、setup script标签内 与 js内用法的区别 setup卸载内部表示立即执行函数,写在内部的所有方法和变量都需要return出去

//写在标签内 组合式API语法糖写法,语法糖大家都知道会让代码变得更简单
1、属性和方法不需要返回,直接使用
2、组件不再需要注册,引入直接使用
3、组件传值变化
    ---emit  子组件通过defineEmits接收父组件传过来的方法 const emits = defineEmits(['sendEmit']);
    子组件调用父组件方法只需要emits('sendEmit', '') 就可以了
    ---父子传值  子组件通过defineProp接收传值,如const props = defineProps ({
  data: {
    type: String
  }
})
console.log(props.data);
<script setup>
</script>

---props传值变化
// 父组件
<template>
  <div class="box" style="margin: 0 auto;text-align: center;">
    <h1>我是父组件</h1>
    <son :data="data"></son>
  </div>
</template>
<script setup>
import son from './son.vue'
const data = '传递给子组件'
</script>
// 子组件 这回不需要props接收了
<template>
<div>
  <h2>我是子组件---{{data}}</h2>
</div>
</template>
<script setup>
const props = defineProps ({
  data: {
    type: String
  }
})
console.log(props.data);
</script>
---emit传值变化
// 子组件
<template>
<div>
  <h2 @click="sendString">我是子组件 点我给父组件传"hello"</h2>
</div>
</template>
<script setup>
const emits = defineEmits(['sendEmit']);
const sendString = function () {
  emits('sendEmit', 'hello')
}
</script>
// 父组件
<template>
  <div class="box" style="margin: 0 auto;text-align: center;">
    <h1>我是父组件</h1>
    <son @sendEmit="sendEmit"></son>
  </div>
</template>
<script setup>
import son from './son.vue'
const sendEmit = function (s) {
  console.log(s);
}
</script>
---对外暴露属性
// 子组件
<template>
<div>
  <h2>我是子组件</h2>
</div>
</template>
<script setup>
import { ref } from 'vue'
let childText = ref('子组件数据')
defineExpose({
    childText,
});
</script>
// 父组件
<template>
  <div class="box" style="margin: 0 auto;text-align: center;">
    <h1 @click="printChildrenText">我是父组件--点我打印子组件值</h1>
    <son ref="sontext"></son>
  </div>
</template>
<script setup>
import son from './son.vue'
import { ref } from 'vue'
let sontext = ref(null)
const printChildrenText = function () {
  console.log(sontext.value.childText);
}
</script> 

 

posted @ 2023-07-30 23:22  iwen1992  阅读(53)  评论(0编辑  收藏  举报