好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

vue3的父传子问题(单项数据流)

vue3父传子(单项数据流)

父组件通过属性绑定传递数据&nbs p;

子组件内部通过 PR ops接收数据 

基本数据类型--- 改变 父组件的数据--只改变了 父组件的的数据在子组件的显示

 

通过动态属性绑定 传递list给子组件

 

在子组件内部修改父组件的复杂数据类型的数据---可以修改 

 

vue3 父子传参 简单 易懂

父传子

1、 在父组件的子组件标签上通过 :传递到子组件的数据名="需要传递的数据"

在这里为了大家区分我将父组件中的数据定义为 : fatherData  ,

子组件需要接收的数据定义为: sonData 。

// 父组件
<template>
  <div class="about">
    {{fatherData}}
    <!-- 父传子 -->
    <!-- 1、 在父组件的子组件标签上通过 :传递到子组件的数据名="需要传递的数据" -->
    <children :sonData="fatherData"></children>
  </div>
</template>
 
<script>
import children  From  "@/ component s/children"
import {  define Component,reactive,toRefs } f rom  "vue";
 export  default defineComponent({
  components:{
    children,
  },
n am e:"about",
 SETUP (){
  const  stat e = reactive({
    fatherData:"hello"
  })
  return {
     .. .toRefs(state)
  }
}
 
})
</script>

2、子组件依旧通过 props 来接收并且在模版中使用

那么大多数情况下都会去通过父组件传递到子组件中的数据,根据这个数据去做一些特定的功能 或者 请求数据 等等 。

在 setup 钩子中第一个参数 props 就可以访问到父组件传递的数据,那么在函数中也是通过:  props.父组件传递数据的名称   来操作该数据。

setup函数接收props作为其第一个参数,props对象是响应式的(单向的父—>子),watchEffect或watch会观察和响应props的更新。不要对props对象进行解构,那样会失去响应性。在开发 过程中 ,props对象对用户空间代码时不可变的,用户尝试修改props时会触发警告。

// 子组件
<template>
  <div class="children">
    <!-- 3、在子组件模版中使用 -->
    {{sonData}}
  </div>
</template>
<script>
e xp ort default {
name:"Children",
// 2、子组件通过 props 来接收
  props:["sonData"],
  setup(props){
    function childrenbut(){
      // props.sonData  可以访问到父组件传递的数据
      console. LOG (props.sonData);
    }
    return {
      childrenbut
    }
  }
}
</script>

子传父

1、子组件触发事件通过 setup 的第二个参数 context.em IT 来实现子传父 

context 上下文对象。

// 子组件
<template>
  <div class="children">
    {{sonData}}
    <!-- 1、触发事件 -->
    <button @click="childrenbut">子组件按钮</button>
  </div>
</template>
<script>
export default {
name:"Children",
  setup(props,context){
    function childrenbut(){
      console.log(context);
      // 2、通过context.emit 实现子传父
      // 第一个参数为  方法名 ,第二个参数为 需要传递的数据
      context.emit("change",'world')
    }
    return {
      childrenbut,
    }
  }
}
</script>

context 也可以使用结构的形式这样写

// 子组件
<script>
export default {
name:"Children",
  // 通过结构 之后直接写 emit {emit}
  setup(props,{emit}){
    function childrenbut(){
      // 省去 context.emit
      emit("change",'world')
    }
    return {
      childrenbut,
    }
  }
}
</script>

最后总结一下:

在 vue3 中无论是父传子还是子传父其实与 vue2 中都相差无几,

思想大多一样,不一样的是 vue3 需要通过调用各种各样的钩子来实现传参。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的 文章 : vue父子组件传值以及单向数据流问题详解 浅谈Vue3 父子传值 Vue3父子组件传参有关sync修饰符的用法详解

总结

以上是 为你收集整理的 vue3的父传子问题(单项数据流) 全部内容,希望文章能够帮你解决 vue3的父传子问题(单项数据流) 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于vue3的父传子问题(单项数据流)的详细内容...

  阅读:54次