101 Provide + Inject To The Rescue

步骤

1、App.vue中使用provide()函数提供数据

provide() {
    return {
      topics: this.topics,
    };
  },

2、在使用到的最下层需要使用该数据的组件中添加inject

<script>
export default {
  inject: ['topics'],
};
</script>

完整代码

App.vue

<template>
  <div>
    <active-element :topic-title="activeTopic && activeTopic.title"
      :text="activeTopic && activeTopic.fullText"></active-element>
    <knowledge-base @select-topic="activateTopic"></knowledge-base>
  </div>
</template>

<script>
export default {
  data() {
    return {
      topics: [
        {
          id: 'basics',
          title: 'The Basics',
          description: 'Core Vue basics you have to know',
          fullText:
            'Vue is a great framework and it has a couple of key concepts: Data binding, events, components and reactivity - that should tell you something!',
        },
        {
          id: 'components',
          title: 'Components',
          description:
            'Components are a core concept for building Vue UIs and apps',
          fullText:
            'With components, you can split logic (and markup) into separate building blocks and then combine those building blocks (and re-use them) to build powerful user interfaces.',
        },
      ],
      activeTopic: null,
    };
  },
  // provide: {
  //   topics: [
  //       {
  //         id: 'basics',
  //         title: 'The Basics',
  //         description: 'Core Vue basics you have to know',
  //         fullText:
  //           'Vue is a great framework and it has a couple of key concepts: Data binding, events, components and reactivity - that should tell you something!',
  //       },
  //       {
  //         id: 'components',
  //         title: 'Components',
  //         description:
  //           'Components are a core concept for building Vue UIs and apps',
  //         fullText:
  //           'With components, you can split logic (and markup) into separate building blocks and then combine those building blocks (and re-use them) to build powerful user interfaces.',
  //       },
  //     ],
  // },
  provide() {
    return {
      topics: this.topics,
    };
  },
  methods: {
    activateTopic(topicId) {
      this.activeTopic = this.topics.find((topic) => topic.id === topicId);
    },
  },
  mounted() {
    setTimeout(() => {
      this.topics.push({
      id: 'vue',
      title: 'Vue',
      description: 'The best framework ever!',
      fullText: 'Vue is the best framework ever!',
    });
    }, 3000);
  },
};
</script>

<style>
* {
  box-sizing: border-box;
}

html {
  font-family: sans-serif;
}

body {
  margin: 0;
}

section {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
  margin: 2rem auto;
  max-width: 40rem;
  padding: 1rem;
  border-radius: 12px;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
}

li {
  border-radius: 12px;
  border: 1px solid #ccc;
  padding: 1rem;
  width: 15rem;
  margin: 0 1rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

h2 {
  margin: 0.75rem 0;
  text-align: center;
}

button {
  font: inherit;
  border: 1px solid #c70053;
  background-color: #c70053;
  color: white;
  padding: 0.75rem 2rem;
  border-radius: 30px;
  cursor: pointer;
}

button:hover,
button:active {
  background-color: #e24d8b;
  border-color: #e24d8b;
}
</style>

ActiveElement.vue

<template>
  <section>
    <h2>{{ topicTitle }}</h2>
    <p>{{ text }}</p>
  </section>
</template>

<script>
export default {
  props: ['topicTitle', 'text'],
};
</script>

KnowledgeBase.vue

<template>
  <section>
    <h2>Select a Topic</h2>
    <knowledge-grid @select-topic="$emit('select-topic', $event)"></knowledge-grid>
  </section>
</template>

<script>
export default {
  emits: ['select-topic'],
};
</script>

KnowledgeGrid.vue

<template>
  <ul>
    <knowledge-element
      v-for="topic in topics"
      :key="topic.id"
      :id="topic.id"
      :topic-name="topic.title"
      :description="topic.description"
      @select-topic="$emit('select-topic', $event)"
    ></knowledge-element>
  </ul>
</template>

<script>
export default {
  inject: ['topics'],
  emits: ['select-topic']
};
</script>

KnowledgeElement.vue

<template>
  <li>
    <h3>{{ topicName }}</h3>
    <p>{{ description }}</p>
    <button @click="$emit('select-topic', id)">Learn More</button>
  </li>
</template>

<script>
export default {
  props: ['id', 'topicName', 'description'],
  emits: ['select-topic'],
};
</script>

main.js

import { createApp } from 'vue';

import App from './App.vue';
import ActiveElement from './components/ActiveElement.vue';
import KnowledgeBase from './components/KnowledgeBase.vue';
import KnowledgeElement from './components/KnowledgeElement.vue';
import KnowledgeGrid from './components/KnowledgeGrid.vue';

const app = createApp(App);

app.component('active-element', ActiveElement);
app.component('knowledge-base', KnowledgeBase);
app.component('knowledge-element', KnowledgeElement);
app.component('knowledge-grid', KnowledgeGrid);

app.mount('#app');

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue.js中,provideinject是一对组件间通信的API,用于实现祖先组件向子孙组件传递数据。provideinject的使用方式类似于React中的Context。 - provide选项是一个可以返回一个对象或函数的函数,在父组件中使用provide提供数据,子孙组件可以通过inject来注入这个数据。provide中的数据会在其所有子孙组件中可用,包括直接子组件和嵌套子组件。 - inject选项是一个数组,其中包含要注入的属性名称列表。这些属性会被注入到组件实例的实例属性中,并且可以直接在组件中使用。如果provide中没有提供对应的属性,则会使用默认值或undefined。 需要注意的是,provideinject不是响应式的。也就是说,当provide中的数据发生改变时,不会触发子孙组件的重新渲染。如果需要实现响应式,可以使用Vue.js的响应式数据实现。 下面是一个简单的示例,展示了如何使用provideinject实现组件间通信: ```javascript // Parent.vue export default { provide: { name: 'parent' }, // ... } // Child.vue export default { inject: ['name'], created() { console.log(this.name) // parent }, // ... } ``` 在上面的示例中,Parent组件使用provide提供了一个名为name的属性,并将其设置为'parent'。Child组件使用inject将name属性注入到自己的实例属性中,并在created钩子函数中打印了该属性的值。因此,当Child组件被创建时,会输出'parent'。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值