一,子传父
父组件
- <script setup>
- import HelloWorld from './components/HelloWorld.vue'
- import { ref } from 'vue'//直接赋值页面不会自动渲染,使用ref存储响应式数据
- import { defineExpose } from "vue";父传子
- let val = ref('');
- const childFun= value =>{
- console.log('----',value)
- // 这里直接赋值value,在页面上直接使用val即可!
- val.value=value
- console.log('val',val)
- }
- </script>
-
- <template>
- <header>
- <div class="wrapper">
- <HelloWorld @child="childFun"/>
- </div>
- </header>
- <div>我是子组件过来的值:{{val}}</div>
- </template>
-
子组件
- <script setup>
- import { defineEmits } from 'vue'//子传父值先引用emits方法
- defineProps({
- msg: {
- type: String,
- required: true
- }
- })
- //要先声明,不然会报错
- const emits = defineEmits(['child'])
- function tofu (){
- emits('child','123')
- }
- </script>
-
- <template>
- <div class="greetings">
- <h1 class="green">msg</h1>
- <button @click="tofu">子组件按钮</button>
- </div>
- </template>
-
二,父传子
父组件
- <script setup>
- import HelloWorld from './components/HelloWorld.vue'
-
- </script>
-
- <template>
- <header>
- <div class="wrapper">
- <HelloWorld msg='我是父组件'/>
- </div>
- </header>
-
- </template>
-
-
子组件
- <script setup>
- defineProps({
- msg: {
- type: String,
- required: true
- }
- })
-
- </script>
-
- <template>
- <div class="greetings">
- <h1 class="green">{{msg}}</h1>
- </div>
- </template>
vue3和vue2区别还是有一些的,V2传值直接赋值,有时是可以直接数据响应渲染
setup可以直接写在script标签上,也可以写成函数形式
const声明的变量,在后期不能进行修改,不然会报错,需后期修改的变量尽量使用let ,var,根据情况使用