组件中传参的方法--(超详细版)

142 阅读1分钟

1. Props(父组件向子组件传递数据):

<template>
  <child-component :propName="value"></child-component>
</template>

<script>
export default {
  data() {
    return {
      value: 'Hello'
    }
  }
}
</script>

2. Emit(子组件向父组件传递数据):

<template>
  <button @click="emitData">Click Me</button>
</template>

<script>
export default {
  methods: {
    emitData() {
      this.$emit('custom-event', 'Data from child component');
    }
  }
}
</script>

3. Provide/Inject(祖先组件向后代组件传递数据):

<template>
  <div>
    <child-component></child-component>
  </div>
</template>

<script>
export default {
  provide() {
    return {
      sharedData: 'Shared data from ancestor component'
    }
  }
}
</script>

子组件:

<template>
  <div>{{ sharedData }}</div>
</template>

<script>
export default {
  inject: ['sharedData']
}
</script>

4. root/root/parent(通过根组件或父组件直接访问数据):

<template>
  <div>{{ $root.sharedData }}</div>
</template>

5. Vuex(使用全局状态管理库Vuex进行数据共享):

<template>
  <div>{{ $store.state.data }}</div>
</template>

6. Event Bus(使用事件总线进行组件间通信):

// Event Bus实例
const EventBus = new Vue();

// 发送事件
EventBus.$emit('custom-event', data);

// 接收事件
EventBus.$on('custom-event', (data) => {
  // 处理数据
});

7. attrs/attrs/listeners(传递父组件未被子组件props接收的属性和事件监听器):

<template>
  <child-component v-bind="$attrs" v-on="$listeners"></child-component>
</template>

8. Refs(通过引用访问子组件的属性和方法):

<template>
  <child-component ref="childRef"></child-component>
</template>

<script>
export default {
  mounted() {
    const childComponent = this.$refs.childRef;
    console.log(childComponent.property); // 访问子组件的属性
    childComponent.method(); // 调用子组件的方法
  }
}
</script>

9. URL 参数(通过URL参数传递数据):

// 发送参数
this.$router.push({ path: '/destination', query: { param: 'value' } });

// 接收参数
this.$route.query.param;

10. Middleware(使用中间件进行数据传递,适用于Vue Router):

// 路由配置
const router = new VueRouter({
  routes: [
    {
      path: '/example',
      component: ExampleComponent,
      meta: {
        data: 'Shared data'
      }
    }
  ]
});

// 中间件定义
router.beforeEach((to, from, next) => {
  const sharedData = to.meta.data;
  // 在这里可以对共享数据进行处理
  next();
});

// 组件内获取共享数据
this.$route.meta.data;

11. Storage(使用浏览器的本地存储进行数据共享):

// 存储数据
localStorage.setItem('key', 'value');

// 获取数据
const data = localStorage.getItem('key');

12. WebSocket(使用WebSocket进行实时数据传递):

// 建立WebSocket连接
const socket = new WebSocket('ws://example.com');

// 发送数据
socket.send('Data to be sent');

// 接收数据
socket.onmessage = (event) => {
  const receivedData = event.data;
};

13. Pub/Sub(使用发布-订阅模式进行组件间通信):

// 创建事件总线
const eventBus = new Vue();

// 发布事件
eventBus.$emit('custom-event', data);

// 订阅事件
eventBus.$on('custom-event', (data) => {
  // 处理数据
});

14. Cookies(使用浏览器的Cookies来传递数据):

// 设置Cookie
document.cookie = 'key=value; expires=Sun, 31 Dec 2023 23:59:59 UTC; path=/';

// 读取Cookie
const cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)key\