js mixins确保不需要重复,可以有效地分配Vue.js组件的可重用功能,并一次又一次地使用它们。
js mixins提供了出色的灵活性,mixin对象包含Vue组件选项,这意味着它是Vue.js的mixin和组件选项的组合。
js mixins提供了出色的安全功能,如果编写得当,它们不会影响超出定义范围的更改。
js mixins是实现代码可重用性的绝佳平台。
<template>
<div>
<button v-on:click="clicked('you just clicked on button 1')">
Button 1
</button>
</div>
</template>;
export default {
name: "Test",
methods: {
clicked(value) {
alert(value);
}
}
};
<template>
<div>
<button v-on:click="clicked('you just clicked on button 2')">
Button 2
</button>
</div>
</template>;
export default {
name: "Modal",
methods: {
clicked(value) {
alert(value);
}
}
};
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<Test />
<modal />
</div>
</template>;
<script>
import Test from "./components/Test.vue";
import Modal from "./components/Modal.vue";
export default {
name: "app",
components: {
Test,
Modal
}
};
</script>
// define a mixin object
var myMixin = {
created: function() {
this.hello();
},
methods: {
hello: function() {
console.log("hello from mixin!");
}
}
};
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
});
var component = new Component(); // => "hello from mixin!"
<html>
<head>
<title>Vue.js </title>
<link rel="stylesheet" href="index.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id = "mixin_1"></div>
<script type = "text/javascript">
var vm = new Vue({
el: '#mixin_1',
data: {
},
methods : {
},
});
var myMixin = {
created: function () {
this.startmixin()
},
methods: {
startmixin: function () {
alert("This is a Vue.js Mixin example!!");
}
}
};
</script>
<script src="index.js"></script>
</body>
</html>
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component()
html, body {
margin: 5px;
padding: 0;
}