mixin 混入
<pre><code class="language-javascript">Student 组件
&lt;template&gt;
&lt;div&gt;
&lt;h2 @click=&quot;showname&quot;&gt;姓名:{{ name }}&lt;/h2&gt;
&lt;h2&gt;性别:{{ sex }}&lt;/h2&gt;
&lt;h2&gt;{{ x }}和{{ y }}&lt;/h2&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
//引入混合
import { hunhe, hunhe2 } from &quot;../mixin&quot;;
export default {
name: &quot;Student&quot;,
data() {
return {
name: &quot;Andy&quot;,
sex: &quot;male&quot;,
};
},
mounted() {
console.log(&quot;我是student的mounted&quot;);
},
mixins: [hunhe, hunhe2],
};
&lt;/script&gt;</code></pre>
<pre><code class="language-javascript">School 组件
&lt;template&gt;
&lt;div&gt;
&lt;h2 @click=&quot;showname&quot;&gt;名称:{{ name }}&lt;/h2&gt;
&lt;h2&gt;地点:{{ address }}&lt;/h2&gt;
&lt;h2&gt;{{ x }}和{{ y }}&lt;/h2&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
//引入混合
import { hunhe, hunhe2 } from &quot;../mixin&quot;;
export default {
name: &quot;School&quot;,
data() {
return {
name: &quot;TKKC&quot;,
address: &quot;Xiamen&quot;,
//混合的优先级低一些
x: 666,
};
},
mounted() {
console.log(&quot;我是school的mounted&quot;);
},
mixins: [hunhe, hunhe2],
};
&lt;/script&gt;</code></pre>
<pre><code class="language-javascript">mixin.js
export const hunhe = {
methods: {
showname() {
alert(this.name)
}
},
mounted() {
console.log('我是mixin')
}
}
export const hunhe2 = {
data() {
return {
x:100,
y:200
}
},
}</code></pre>
<pre><code class="language-javascript">App 组件
&lt;template&gt;
&lt;div&gt;
&lt;Student&gt;&lt;/Student&gt;
&lt;hr&gt;
&lt;School&gt;&lt;/School&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import Student from './components/Student.vue'
import School from './components/School.vue'
export default {
name:'App',
components:{Student,School}
}
&lt;/script&gt;</code></pre>
<p><img src="https://www.showdoc.com.cn/server/api/attachment/visitfile/sign/f6c9a50733c9b62ea733891b3c47c6d0" alt="" /></p>