VUE3知识点总结 之 setup(一)

简介: VUE3知识点总结 之 setup(一)

7c8d194338df4c4f8ef1e5bdb07dc225.png


setup


起初 Vue3.0 暴露变量必须 return 出来,template中才能使用,之Vue3.2起只需在script标签中添加setup,组件只需引入不用注册,属性和方法也不用返回,也不用写setup函数,也不用写export default ,甚至是自定义指令也可以在我们的template中自动获得


使用setup后新增API


因为没有了setup函数,之前setup函数接受的两个参数 props 与 content 自然也没有了,那么怎么使用 props 与 content 参数呢,setup script 提供了新的API供使用


defineProps


用来接收父组件传来的 props。示例


父组件代码


<template>
  <div class="die">
    <h3>我是父组件</h3>
    <chile :name="name"></chile>
  </div>
</template>
<script setup>
  import chile from './chile'
  import {ref} from 'vue'
  let name = ref('儿子')
</script>


子组件代码


<template>
  <div>子组件 {{ name }}</div>
</template>
<script setup>
  import { defineProps } from 'vue'
  defineProps({
   name:{ type:String, required: true }
 })
</script>


defineEmits


子组件向父组件事件传递


子组件


<template>
  <div>
    子组件 {{ name }}
    <button @click="ziupdata">按钮</button>
  </div>
</template>
<script setup>
  import { defineEmits } from 'vue'
  //自定义函数,父组件可以触发
  const emUpdate = defineEmits(['updata'])
  const ziupdata = () => { emUpdate("updata",'子组件的值') }
</script>


父组件


<template>
  <div>
    <child @updata="updata"></child>
  </div>
</template>
<script setup>
  import child from './child'
  const updata = (data) => {
    console.log(data); // 子组件的值
  }
</script>


defineExpose


组件暴露出自己的属性,在父组件中可以拿到。示例:


子组件


<template>
  <div>子组件</div>
</template>
<script setup>
  import { defineExpose, reactive, ref } from 'vue'
  let ageList = ref([1, 2, 3])
  let nameList = reactive({ name: '狂徒张三'})
  // 暴露出去的变量
  defineExpose({
    ageList,
    nameList
  })
</script>


父组件


<template>
  <div class="die">
    <h3 @click="isclick">父组件</h3>
    <chile ref="chile"></chile>
  </div>
</template>
<script setup>
  import chile from './chile'
  import { ref } from 'vue'
  const chile = ref(null)
  const isclick = () => {
    console.log('暴漏出来的值',chile.value.ageList)
    console.log('暴漏出来的值',chile.value.nameList.name)
  }
</script>
目录
相关文章
|
1天前
|
JavaScript
vue知识点
vue知识点
11 4
|
3天前
|
JavaScript 定位技术 API
在 vue3 中使用高德地图
在 vue3 中使用高德地图
9 0
|
3天前
vue3 键盘事件 回车发送消息,ctrl+回车 内容换行
const textarea = textInput.value.textarea; //获取输入框元素
13 3
|
6天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
18 0
|
6天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
6天前
|
JavaScript 前端开发 安全
Vue3官方文档速通(下)
Vue3官方文档速通(下)
16 0
|
6天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
22 0
|
6天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
32 0
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
10 1
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
13 0