Vue学习-父子组件通信

父子组件通信

1. 父传子props

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <cpn v-bind:cmovies="movies"></cpn>
  </div>
  <template id="cpn">
    <div>
      <ul>
        <li v-for="item in cmovies">{{item}}</li>
      </ul>
    </div>
  </template>
  <script src="../js/vue.js">
  </script>
  <script>
    //父传子: props
    const cpn = {
      template: '#cpn',
      // props:['cmovies'],
      props: {
        // cmovies: Array,
        cmovies: {
          type: Array,
          default(){
            return []
          },
          required: true,
        },
      },
      data() {
        return {
          
        }
      },
    }
    const app = new Vue({
      el: '#app',
      data: {
        message: 'hello',
        movies: ['海王','QT','FCLC'],
      },
      components: {
        cpn
      }
    })
  </script>
</body>
</html>

v-bind不支持驼峰:HTML不区分大小写

子传父:自定义事件

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <cpn @btnclick="cpnClick"></cpn>
  </div>
  <template id="cpn">
    <div>
      <ul>
        <li v-for="item in categories" @click="itemClick(item)"><button>{{item.name}}</button></li>
      </ul>
    </div>
  </template>
  <script src="../js/vue.js">
  </script>
  <script>
    const cpn = {
      template: '#cpn',
      
      data() {
        return {
          categories: [
            {id:'a',name:'热门推荐'},
            {id:'b',name:'手机数码'},
            {id:'c',name:'家用电器'},
            {id:'d',name:'电脑办公'},
          ]
        }
      },
      methods: {
        itemClick(item){
          this.$emit('btnclick',item);
        }
      },
    }
    const app = new Vue({
      el: '#app',
      data: {
        message: 'hello',
        movies: ['海王','QT','FCLC'],
      },
      components: {
        cpn
      },
      methods: {
        cpnClick(item){
          console.log(item.name);
        },
      },
    })
  </script>
</body>
</html>
Vue 3 和 TypeScript 中,父子组件通信有多种方法,以下是详细介绍及示例: ### 简单数据传递:Props/Events - **Props**:父组件向子组件传递数据。在父组件中,将数据作为属性绑定到子组件上;子组件使用 `defineProps` 接收数据。 ```vue <!-- 父组件 Parent.vue --> <template> <div> <Child :message="parentMessage" /> </div> </template> <script setup lang="ts"> import Child from './Child.vue'; const parentMessage = 'Hello from parent'; </script> <!-- 子组件 Child.vue --> <template> <div>{{ message }}</div> </template> <script setup lang="ts"> const props = defineProps<{ message: string }>() </script> ``` - **Events**:子组件向父组件发送数据或通知。子组件使用 `defineEmits` 定义可触发的事件,通过 `emit` 触发事件;父组件在使用子组件时监听事件。 ```vue <!-- 父组件 Parent.vue --> <template> <div> <Child @childEvent="handleChildEvent" /> </div> </template> <script setup lang="ts"> import Child from './Child.vue'; const handleChildEvent = (data: string) => { console.log('Received data from child:', data); }; </script> <!-- 子组件 Child.vue --> <template> <button @click="sendDataToParent">Send data to parent</button> </template> <script setup lang="ts"> const emit = defineEmits<{ (e: 'childEvent', data: string): void }>() const sendDataToParent = () => { emit('childEvent', 'Data from child'); }; </script> ``` ### 使用 `defineExpose` 暴露子组件方法 在子组件中使用 `defineExpose` 函数定义要暴露给父组件的内容,父组件通过 `ref` 引用子组件并访问其暴露的方法。 ```vue <!-- 父组件 Parent.vue --> <template> <div> <Child ref="childRef" /> <button @click="callChildMethod">Call child method</button> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import Child from './Child.vue'; const childRef = ref<InstanceType<typeof Child> | null>(null); const callChildMethod = () => { childRef.value?.childMethod(); }; </script> <!-- 子组件 Child.vue --> <template> <div>Child component</div> </template> <script setup lang="ts"> const childMethod = () => { console.log('Child method called'); }; defineExpose({ childMethod }); </script> ``` ### 使用 `useAttrs` 获取组件属性与事件 `useAttrs` 是 Vue 3 框架提供的方法,可以获取组件身上的属性与事件。 ```vue <!-- 父组件 Parent.vue --> <template> <div> <HintButton type="primary" size="small" title="编辑按钮" @click="handler" /> </div> </template> <script setup lang="ts"> import HintButton from './HintButton.vue'; const handler = () => { alert(12306); }; </script> <!-- 子组件 HintButton.vue --> <template> <button @click="$attrs.onClick">Click me</button> </template> <script setup lang="ts"> import { useAttrs } from 'vue'; const attrs = useAttrs(); </script> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值