在vue中提供了一种复用性的操作,所混入的对象包含任意组件的选项(data|computed,生命周期|watch,methods)

-
- <div id="app">
- <div>data里面的数据:{{msg}}div>
- <div>computed里面的数据:{{title}}div>
- <div>watch里面的数据:{{obj.a}}div>
- <button @click="getMsg">获取方法的数据button>
- div>
- <script>
- const HomeMixin = {
- data() {
- return {
- msg: "home的msg",
- obj: {
- a: "home watch里面的数据a"
- }
- }
- },
- computed: {
- title() {
- return this.msg + "在computed里面"
- }
- },
- watch: {
- 'obj.a': function () {
- console.log("home里面watch对象的属性obj.a的变化");
- }
- },
- mounted() {
- console.log("home的生命周期方法mounted");
- },
- methods: {
- getMsg() {
- console.log("home的methods");
- }
- }
- };
-
- new Vue({
- el: "#app",
- mixins: [HomeMixin],
- data() {
- return {
- msg: "index msg",
- obj: {
- a: 1
- }
- }
- },
- computed: {
- title() {
- return this.msg + "--computed"
- }
- },
- watch: {
- 'obj.a': function () {
- console.log("index页面里面watch对象的属性obj.a的变化");
- }
- },
- mounted() {
- console.log("index页面的生命周期方法mounted");
- },
- methods: {
- getMsg() {
- this.obj.a = "ss"
- console.log("index页面的methods里面的方法getMsg");
- }
- }
- });
- script>
在main.js入口文件中使用Vue.mixin()引入。
尽量不用使用mixin全局混入,它将影响每一个之后创建的 Vue 实例(包括第三方插件 )
- // 为自定义的选项 'myOption' 注入一个处理器。
- Vue.mixin({
- created: function () {
- var myOption = this.$options.myOption
- if (myOption) {
- console.log(myOption)
- }
- }
- })
-
- new Vue({
- myOption: 'hello!'
- })