PHP前端开发

vue子组件数据怎么用

百变鹏仔 3周前 (09-25) #VUE
文章标签 组件
vue 子组件数据独立于父组件,只能访问通过 props 传递的数据。父组件使用 v-bind 指令和 props 选项向子组件传递数据。子组件使用 $attrs 访问除 props 声明外的父组件属性。子组件通过自定义事件向父组件传递数据。

Vue 子组件数据使用

在 Vue.js 中,子组件的数据与父组件的数据是分开的。子组件只能访问父组件通过 props 属性传递给它的数据。父组件可以通过 v-bind 指令向子组件传递数据。

使用 Props 传递数据

在子组件中,使用 props 选项指定需要接收的数据:

立即学习“前端免费学习笔记(深入)”;

export default {  props: ['data']};

在父组件中,使用 v-bind 指令传递数据:

<template><childcomponent v-bind:data="myData"></childcomponent></template><script>export default {  data() {    return {      myData: 'Hello Vue!'    }  }};</script>

使用 $attrs 访问额外属性

除了 props 之外,子组件还可以通过 $attrs 访问父组件传递的其他属性,这些属性没有在 props 中显式声明。

在子组件中:

export default {  mounted() {    console.log(this.$attrs.extraAttribute);  }};

在父组件中:

<template><childcomponent v-bind:data="myData" extra-attribute="foo"></childcomponent></template>

使用自定义事件

如果子组件需要向父组件传递数据,可以使用自定义事件。

在子组件中:

export default {  methods: {    emitData() {      this.$emit('update-data', 'New data');    }  }};

在父组件中:

<template><childcomponent></childcomponent></template><script>export default {  methods: {    handleData(newData) {      // 处理新数据    }  }};</script>