[英]How to reuse a SFC Vue component instance in different components?
Motivation :动机:
I have a single file component, say Player, which displays video or show some images.我有一个文件组件,比如播放器,它显示视频或显示一些图像。 Since it costs huge amount of memory, and it is used in many pages (components under root), I want to instantiate it only once and reuse it in every page depending on it.
由于耗资巨大,memory,并且在很多页面(root下的组件)中使用,所以我只想实例化一次,并在依赖它的每个页面中重用它。 Also, Player is resized for some pages, so I need it to be dynamically adjustable, which means it should support props.
此外,Player 会针对某些页面调整大小,因此我需要它可以动态调整,这意味着它应该支持道具。 Furthermore, since there are many pages using Player, I hope I can use
Provide / Inject
feature of Vue to spreading Player everywhere.此外,由于有很多页面使用播放器,我希望我可以使用 Vue 的
Provide / Inject
功能来到处传播播放器。
Current :当前:
// Player
<template>
<div>
... // display images and video
</div>
</template>
<script>
export default Vue.extend({
props: {
width: {
type: Number,
default: 284,
},
height: {
type: Number,
default: 214,
},
},
data() {
... // images and video
},
methods: {
... // logic related to images and video
},
})
// An example of `pages`
<template>
<div>
<player
:width="592"
:height="333"
/>
... // some other logic
</div>
</template>
... // everything else
Expect :期望:
To sum up, Player has these features in my imagination:总结一下,Player在我的想象中有这些特点:
Provide
Player to every component under it.Provide
Player 给它下面的每个组件。Injected
Player somehow to resize it. Injected
的播放器以调整其大小。 This is just my imagination, any other available solution is welcome.这只是我的想象,欢迎任何其他可用的解决方案。
What I've tried :我试过的:
There are two ways to do this-有两种方法可以做到这一点-
main.js
file and use on any page freely.main.js
文件中的组件,任意页面自由使用。 ie- import Vue from "vue";
import Player from "@/components/Player.vue";
Vue.component("AppButton", AppButton);
playerMixin.js
inside the mixins
directory.mixins
目录中创建一个名为playerMixin.js
的 mixin。 playerMixin.js playerMixin.js
import Player from "@/components/Player.vue";
export const playerMixin = {
data() {
// any data properties related to player functionalities
},
components: {
Player,
},
methods: {
// any methods related to player functionalities
}
}
Now, you can use this mixin on any page, like this-现在,你可以在任何页面上使用这个 mixin,就像这样 -
AnyPage.vue AnyPage.vue
import { playerMixin} from "@/mixins/playerMixin.js";
export default {
name: "AnyPage",
mixins: [playerMixin],
}
The main benefit of using mixin is that not only components will be imported once but the common functionality of Player which is the same for every page like passing props, and methods like play, a pause can be written once and can be used by any page.使用 mixin 的主要好处是不仅组件会被导入一次,而且 Player 的通用功能在每个页面都是相同的,例如传递 props,以及像播放、暂停这样的方法,只需编写一次,就可以被任何页面使用.
To understand more about mixin, read this .要了解有关 mixin 的更多信息,请阅读此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.