我事先表示歉意,但总体而言,我对Vuejs还是很陌生。我正在尝试将CreateJS / SoundJS导入.vue组件。我已经通过npm安装了CreateJS。我只是不知道如何将库导入到组件中,因此我可以引用声音函数。对于这种使用方式,我似乎在CreateJS文档中找不到任何东西……任何代码或参考链接都将不胜感激。谢谢!
答案 0 :(得分:2)
好吧,我使用CreateJS / SoundJS库从CDN导入示例。
在public / index.html文件中,添加标签:
<script src="https://code.createjs.com/1.0.0/soundjs.min.js"></script>
现在,您的项目中已有该库,并且可以访问它及其功能。
在src / main.js中,添加要与Vue一起使用的库,将其添加到Vue原型中:
import Vue from "vue";
import App from "./App.vue";
const createjs = window.createjs; // Get the createjs instance from window object
Vue.config.productionTip = false;
Vue.prototype.createjs = createjs; // Add the createjs instance to the Vue prototy, to use this.createjs
new Vue({
render: h => h(App)
}).$mount("#app");
在src / App.vue组件(或任何组件中,但App.vue是应用程序的入口点,因此是执行此操作的好地方)中配置声音:
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
<button @click="play">Play</button>
<!-- button to call the play method -->
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
const hornSound = require("@/assets/hey.mp3"); // Store a mp3 file in a variable, You can add more sounds, here on in another components
export default {
name: "App",
components: {
HelloWorld
},
methods: {
play() {
this.createjs.Sound.play("Horn"); // Acces and play the sound with the id "Horn"
}
},
created() {
const soundId = "Horn"; // Id of the sound to be registered
this.createjs.Sound.registerSound(hornSound, soundId); // Register the sound, using the mp3 and the id
// You can do this with any amount of sounds, here or in any component
// Once a sound is registered, you have access to it in all the components
}
};
</script>
播放子组件(src / components / HelloWorld.vue)中的声音:
<template>
<div class="hello">
<h3>Hello World with createjs/soundjs</h3>
<button @click="playFromChild">Play inside child component</button>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
},
methods: {
playFromChild() {
this.createjs.Sound.play("Horn"); // We are accessing to the sound with id "Horn" without import anything
}
}
};
</script>
希望对您有所帮助,我试图解释如何使用它,但是正如您所说的,没有关于它的文档,所以也许这很棘手,但是有效。