vue里面全局mixin和局部mixin

74 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    // 定义一个局部的混入const  mixin
    const myMixIn = {
      data() {
        return {
          count: 11111,
        };
      },
    };
    // 跟组件,里面引入这个混入mixins:[],这里不是父组件的变量,所以[]里面不用加“”
    // 跟组件里面用了子组件Son,用了一个变量hello
    const app = Vue.createApp({
      mixins: [myMixIn],
      template: `
<h1>{{count}}</h1>
<h1>{{hello}}</h1>
<Son />
`,
    });
    // 定义Son组件,子组件也用了变量hello
    app.component("Son", {
      template: `
        <div>{{hello}}</div>
        `,
    });
    // 定义全局mixin,全局的不用在组件里面minxins接收
    // 跟组件和子组件都用到了hello这个变量,所以在全局mixin里面定义
    app.mixin({
      data() {
        return {
          hello: "hello world",
        };
      },
    });
    const vm = app.mount("#root");
  </script>
</html>